在不重启应用程序服务器或在运行时重新初始化 spring 个 beans
Re-Initialize spring beans without app server restart or at runtime
有没有办法动态地重新初始化 spring bean?
在应用程序启动时,我在 web.xml 中通过 ContextLoaderListener 初始化 spring 个 bean。
我的用例是,在运行时可能会出现新的 属性 文件被加载到内存中的情况(通过 Apache commons 配置),我想重新初始化这些 bean,这样它就可以在不影响的情况下生效不得不重新启动。
感谢任何对此的指点。
能够通过 class 实现 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?
在应用程序启动时,我在 web.xml 中通过 ContextLoaderListener 初始化 spring 个 bean。
我的用例是,在运行时可能会出现新的 属性 文件被加载到内存中的情况(通过 Apache commons 配置),我想重新初始化这些 bean,这样它就可以在不影响的情况下生效不得不重新启动。
感谢任何对此的指点。
能够通过 class 实现 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;
}