替换Bean工具类
@Component
public class ApplicationContextUtil implements ApplicationContextAware {private static ApplicationContext applicationContext = null;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {if(this.applicationContext == null) {this.applicationContext = applicationContext;}}public static ApplicationContext getApplicationContext() {return applicationContext;}public static <T> T getBean(Class<T> clazz) {return getApplicationContext().getBean(clazz);}public static void replaceBean(String beanName, Object targetObj) throws NoSuchFieldException, IllegalAccessException {ConfigurableApplicationContext context = (ConfigurableApplicationContext)getApplicationContext();DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();//反射获取Factory中的singletonObjects 将该名称下的bean进行替换Field singletonObjects = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");singletonObjects.setAccessible(true);Map<String, Object> map = (Map<String, Object>) singletonObjects.get(beanFactory);map.put(beanName, targetObj);}
}
使用
@Autowiredprivate TestBean testBean;@Testpublic void updateBean() throws NoSuchFieldException, IllegalAccessException {System.out.println("before: " + testBean);ApplicationContextUtil.replaceBean("testBean", new TestBean("qq", 100));testBean = ApplicationContextUtil.getBean(TestBean.class);System.out.println("after: " + testBean);}
测试类
public class TestBean {String name;int age;public TestBean(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "TestBean{" +"name='" + name + '\'' +", age=" + age +'}';}
}
初始化Bean
@Beanpublic TestBean testBean(){return new TestBean("dreamzuora", 25);}