问题
Is there a way to re-initialize the spring beans dynamically ?
On app startup I Initialize spring beans through ContextLoaderListener in web.xml.
My use case is that at runtime there could be a case where new property files were loaded into memory(via Apache commons configuration) and I want to reinitialize the beans so that this can take into affect without having to restart.
Any pointers on this is appreciated.
回答1:
Was able to solve it by having the class implement ApplicationContextAware
public class ReloadConfig implements ApplicationContextAware{
private static Logger log = Logger.getLogger(ReloadConfig.class);
private Config config;
@Autowired
ApplicationContext applicationContext;
private ReloadConfig() {
// Exists only to defeat instantiation.
config = Config.getInstance();
}
public void reloadIfNotLoaded() throws ConfigurationException{
CompositeConfiguration configuration = new CompositeConfiguration();
if(config.getHealthFile() == null){
log.info("Reloading Adding default properties found in config.properties");
configuration.addConfiguration(new PropertiesConfiguration("config.properties"));
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext)getApplicationContext();
configurableApplicationContext.refresh();
setApplicationContext(configurableApplicationContext);
}
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
来源:https://stackoverflow.com/questions/29354880/re-initialize-spring-beans-without-app-server-restart-or-at-runtime