Re-Initialize spring beans without app server restart or at runtime

纵饮孤独 提交于 2020-01-01 19:39:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!