Affects: spring-beans-5.1.16.RELEASE
我使用的包: spring-beans-5.1.16.RELEASE.jar the bug package: spring-beans-5.1.16.RELEASE.jar
场景:
项目中,我想动态的替换bean对象(也就是可以手动替为我想要的bean), 在使用过程中,第一次第二次替换是正常,
当我在第三次替换是不正常,代码截图如下
多次访问打印时的日志如下:
我想要的效果是不管我访问多少次testChangeBean方法, applicationContext.getBean(BeanService.class) 与 beanService 值是相等,但是实际结果,是我在第3次执行访问testChangeBean方法时,他们不相等. beanService 一直保留旧的值。
经过代码调试发现, 调用BeanDefinitionRegistry.registerBeanDefinition(String, BeanDefinition)并没有立即初使化完成。是使用懒加载机制,也就是在下一次访问beanService 属性时会去更新到最新的bean对象; 再执行BeanDefinitionRegistry.registerBeanDefinition(String, BeanDefinition)时,再访问beanService时就不再更新它了,这时beanService就一值保留旧的值。有没有什么好的方法可以改变这种状况
Comment From: bclozel
As explained in the reference documentation, there's a lifecycle issue with your approach. You're not supposed to register new bean definitions once the context is started.