How can I update all spring objects after setting

2020-03-25 01:18发布

问题:

How can I refresh previously @Autowired spring objects after dynamic configuration changes?

// Here is my updateConfig method

GenericApplicationContext context = new GenericApplicationContext();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
reader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
context.refresh();

myApplicationContextAware.setApplicationContext(context);

With myApplicationContextAware.applicationContext.getBean(MyClass.class) I can get new instances by new configuration, but all @Autowired objects still contain old values

Is there any solution to refresh spring objects?

回答1:

You can use AbstractRefreshableApplicationContext for this. It provides methods to reload bean configuration in run time.

If you're using spring boot then you can use @RefreshScope annotation with the spring actuator. Spring actuator endpoint /refresh reloads the beans annotated with @RefreshScope.