spring boot 如何动态替换bean?
生活随笔
收集整理的這篇文章主要介紹了
spring boot 如何动态替换bean?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
替換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);}總結
以上是生活随笔為你收集整理的spring boot 如何动态替换bean?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springmvc与mybatis整合之
- 下一篇: Mybatis输入映射和输出映射