簡體   English   中英

在不重新啟動應用服務器或運行時重新初始化spring bean

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

有沒有辦法動態地重新初始化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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM