在没有应用程序服务器重启或运行时初始化spring bean
有没有办法动态地重新初始化Spring Bean?
在应用程序启动时,我通过web.xml中的ContextLoaderListener初始化spring bean。
我的用例是,在运行时可能会出现新属性文件加载到内存中的情况(通过Apache commons配置),我想重新初始化这些bean,以免影响而无需重新启动。
任何指针在这是赞赏。
能够通过让类实现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;
}
链接地址: http://www.djcxy.com/p/82037.html
上一篇: Initialize spring beans without app server restart or at runtime