编码方式注册及移除注册bean
SpringBeanRegisterUtil.java
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 BeanDefinitionBuilderBeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(className); // get the BeanDefinitionBeanDefinition beanDefinition=beanDefinitionBuilder.getBeanDefinition();// register the beanbeanDefinitionRegistry.registerBeanDefinition(beanId,beanDefinition); }/** unregister the bean */public static void unregisterBean(String beanId){beanDefinitionRegistry.removeBeanDefinition(beanId);}}