springboot 工程如果项目有需求加载非本工程内的配置文件,我们应该怎么设置
SpringBoot 加载外部配置文件
SpringBoot 默认加载配置文件是由SpringBoot默认声明的目录路径所加载,如果说是classpath下
我们可以在SpringBoot启动类中设置环境参数,让SpringBoot加载所指定的目录
参数设置如下
SpringApplication application = new SpringApplication(SpringBootDemoApplication.class);// 设置环境ConfigurableEnvironment environment = new StandardEnvironment();MutablePropertySources propertySources = environment.getPropertySources();Map myMap = new HashMap<>();// 这里设置配置文件所在地址myMap.put("spring.config.location", "D:\\");propertySources.addFirst(new MapPropertySource("MY_MAP", myMap));application.setEnvironment(environment);application.run(args);
我们设置了配置文件的地址为D盘下面,SpringBoot 启动的时候就会在D盘下进行查询配置文件,不会在classpath中进行查找
通过Idea设置环境变量
如果是JAR包则使用如下配置
java -jar app.jar --spring.config.location=D:\\
springboot在获取配置文件所在目录的时候先判断 环境中是否手动设置了配置文件目录
源码是如何跟踪到这里的可以看一下我这篇文章
下面我们看一下这个方法中都做了什么操作,这里环境的对象就回去判断是否包含spring.config.location 这个属性,这个属性就是我们在上面所配置的属性。
显然这里是包含的,所以SpringBoot会获取到这个执行,进行格式处理后进行返回,不会走默认的目录方法
还请多多指教