SpringBoot 加载外部配置文件 不重启服务 自动更新外部配置

常规启动类:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}

 

加载外部配置文件启动类:

工具类

package cn.com.aia.robot.util;

import cn.com.aia.robot.ReleaseRobotsApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class ApplicationContextUtils {

    private static String[] args;
    private static ApplicationContext context;

    private ApplicationContextUtils() {
    }

    public static void init(ApplicationContext applicationContext, String[] args) {
        ApplicationContextUtils.context = applicationContext;
        ApplicationContextUtils.args = args;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        ApplicationContextUtils.context = applicationContext;
    }

    public static void setArgs(String[] args) {
        ApplicationContextUtils.args = args;
    }

    /**
     * 刷新ConfigurableApplicationContext,实现不重启服务,自动更新配置
     * Resource resource指向外部配置文件
     */
    public static void restart(Resource resource) throws Exception {
        if(context instanceof ConfigurableApplicationContext) {
            ((ConfigurableApplicationContext) context).close();
            SpringApplication app = new SpringApplication(ReleaseRobotsApplication.class);
            app.setDefaultProperties(PropertiesLoaderUtils.loadProperties(resource));
            ConfigurableApplicationContext applicationContext = app.run(args);
            ApplicationContextUtils.setApplicationContext(applicationContext);
        }
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
}

 

启动类

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setDefaultProperties(PropertiesLoaderUtils.loadProperties(new PathResource(Paths.get("C:/xxx/xxx.properties"))));
        //app.setDefaultProperties(PropertiesLoaderUtils.loadProperties(new UrlResource("http://xxx/xxx.properties")));
        ConfigurableApplicationContext applicationContext = app.run(args);
        ApplicationContextUtils.init(applicationContext, args);
    }
}

 

posted @ 2021-02-04 17:18  Bevis  阅读(1267)  评论(0编辑  收藏  举报