[size=large]SpringBeanRegisterUtil.java[/size]
package utils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringBeanRegisterUtil {
private static ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
private static ConfigurableApplicationContext configurableContext =
(ConfigurableApplicationContext) context;
private static BeanDefinitionRegistry beanDefinitionRegistry =
(DefaultListableBeanFactory) configurableContext.getBeanFactory();
/** register the bean */
public static void registerBean(String beanId,String className) {
// get the BeanDefinitionBuilder
BeanDefinitionBuilder beanDefinitionBuilder =
BeanDefinitionBuilder.genericBeanDefinition(className);
// get the BeanDefinition
BeanDefinition beanDefinition=beanDefinitionBuilder.getBeanDefinition();
// register the bean
beanDefinitionRegistry.registerBeanDefinition(beanId,beanDefinition);
}
/** unregister the bean */
public static void unregisterBean(String beanId){
beanDefinitionRegistry.removeBeanDefinition(beanId);
}
}