package jfun.yan.xml.nuts.spring;
import jfun.yan.Component;
import jfun.yan.lifecycle.DefaultLifecycleManager;
import jfun.yan.lifecycle.Procedure;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.context.ApplicationContext;
/**
* SpringService contains all Spring-related data.
* <p>
* @author Ben Yu
* Nov 20, 2005 5:31:22 PM
*/
public class SpringService {
private final ApplicationContext actxt;
private final DefaultLifecycleManager.DefaultLifecycle bean_lifecycle;
private final BeanPostProcessorQueue processors = new BeanPostProcessorQueue();
//private final BeanPostProcessorQueue instantiations = new BeanPostProcessorQueue();
private final BeanPostProcessorQueue destructions = new BeanPostProcessorQueue();
/**
* Create a SpringService object.
* @param actxt the ApplicationContext object.
* @param manager the lifecycle manager.
*/
public SpringService(ApplicationContext actxt, DefaultLifecycleManager manager){
this.actxt = actxt;
this.bean_lifecycle = getDisposerLifecycle(manager);
}
private static final class BeanDisposer{
//wrap around the DisposableBean so that this lifecycle does not
//overlap with the default Yan lifecycle.
private final DisposableBean db;
BeanDisposer(DisposableBean db) {
this.db = db;
}
void dispose()
throws Exception{
db.destroy();
}
}
private static DefaultLifecycleManager.DefaultLifecycle
getDisposerLifecycle(DefaultLifecycleManager manager){
return manager.newLifecycle().disposer(new Procedure(){
public void invoke(Object self, Object[] args)
throws Throwable {
final BeanDisposer bd = (BeanDisposer)self;
bd.dispose();
}
});
}
/**
* Get the ApplicationContext object.
*/
public ApplicationContext getApplicationContext(){
return actxt;
}
/**
* Report an existence of a DisposableBean object.
* @param db the DisposableBean object.
*/
public void manageDisposableBean(DisposableBean db){
bean_lifecycle.manageInstance(new BeanDisposer(db));
}
/**
* Report an existence of a Component that instantiates BeanPostProcessor.
* @param key the key of the component.
* @param type the type of the component.
* @param bpp the component that instantiates BeanPostProcessor.
*/
public void addBeanPostProcessor(String key, Class type, Component bpp){
if(DestructionAwareBeanPostProcessor.class.isAssignableFrom(type)){
destructions.addBeanPostProcessor(key, bpp);
}
if(BeanPostProcessor.class.isAssignableFrom(type)){
processors.addBeanPostProcessor(key, bpp);
}
}
/**
* Get all the BeanPostProcessor components.
*/
public BeanPostProcessorQueue getProcessorQueue(){
return processors;
}
/**
* Get all the DestructionAwareBeanPostProcessor components.
*/
public BeanPostProcessorQueue getDestructionAwares(){
return destructions;
}
}