在不重新启动应用服务器或运行时重新初始化spring bean [英] Re-Initialize spring beans without app server restart or at runtime
问题描述
有没有一种方法可以动态地重新初始化spring bean?
Is there a way to re-initialize the spring beans dynamically ?
在应用启动时,我通过web.xml中的ContextLoaderListener初始化spring Bean.
On app startup I Initialize spring beans through ContextLoaderListener in web.xml.
我的用例是,在运行时可能会出现这样的情况:新属性文件(通过Apache commons配置)加载到内存中,并且我想重新初始化Bean,以便无需重新启动即可生效.
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.
推荐答案
能够通过使该类实现ApplicationContextAware来解决它
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;
}
这篇关于在不重新启动应用服务器或运行时重新初始化spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!