在pom.xml中设置<profiles>标签来指定配置文件加载路径
<profiles>
<profile>
<id>local</id>
<build>
<resources>
<resource>
<directory>src/main/profile</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
resources属性指定了配置文件资源的路径
id是可以为maven在编译的时候指定对应值然后使用对应id的profile
activationByDefault属性指定该profile为默认加载profile
如果在编译时mvn -P local命令,这样就会加载id为local的profile
设置完profile之后,运行程序,会看到target/classes目录下有application.properties文件,打开一看,为自己的配置文件。
那profile里不是设置了两个路径吗?src/main/profile和src/main/resources,为什么只有一个application.properties?src/main/resources下的配置文件里没有写任何配置,但是这个配置文件为啥没有加载到classpath下?
试着调整pom.xml里的profiles设置如下:
<profiles>
<profile>
<id>local</id>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/profile</directory>
</resource>
</resources>
</build>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
再次运行,发现程序报错,找不到配置,进入target/classes里一看,application.properties里啥也没有。
综上可以得出,pom.xml里profile的路径会从下至上的加载,这样如果有同名的文件,上面的profile路径的会覆盖下面的。
如果将两个路径里的配置文件改成不一样的名字,则target/classes里两个属性配置文件都有了。
但是这时候需要在spring boot主类前加上新属性文件的注解:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@PropertySource("classpath:app.properties")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
大功告成!