有没有办法动态重新初始化spring bean?
在应用启动时,我通过web.xml中的ContextLoaderListener初始化spring bean。
我的用例是,在运行时可能会出现新属性文件被加载到内存中的情况(通过Apache commons配置),我想重新初始化bean,这样就可以在不重新启动的情况下生效。
对此的任何指示表示赞赏。
答案 0 :(得分:1)
能够通过让类实现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;
}