我不得不试验来说服自己。
从Spring Initializr创建最简单的 Spring Boot 应用程序
然后将 3 个属性文件添加到资源目录(第一个已经存在但为空)
# application.properties
foo=foo in application.properties
bar=bar in application.properties
baz=baz in application.properties
# application-foobar.properties
foo=foo in foobar override properties
bar=bar in foobar override properties
# application-barbaz.properties
bar=bar in barbaz override properties
baz=bar in barbaz override properties
然后我添加了这个@Config 类在启动时运行:
package com.example.profilesexperiment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
class StartupConfig {
@Autowired
private Environment environment;
@Value("${foo}")
private String foo;
@Value("${bar}")
private String bar;
@Value("${baz}")
private String baz;
@Bean
CommandLineRunner startup() {
return args -> {
System.err.println("Active profiles: " + String.join(", ", environment.getActiveProfiles()));
System.err.println("Foo = " + foo);
System.err.println("Bar = " + bar);
System.err.println("Baz = " + baz);
};
}
}
然后我用不同的配置文件组合运行它。您可以自己尝试,但这里有一些输出:
只是 foobar
java -Dspring.profiles.active=foobar -jar target/profiles-experiment-0.0.1-SNAPSHOT.jar
Active profiles: foobar
Foo = foo in foobar override properties
Bar = bar in foobar override properties
Baz = baz in application.properties
foobar 然后 barbaz
java -Dspring.profiles.active=foobar,barbaz -jar ...
Active profiles: foobar, barbaz
Foo = foo in foobar override properties
Bar = bar in barbaz override properties
Baz = bar in barbaz override properties
barbaz 然后 foobar
java -Dspring.profiles.active=barbaz,foobar -jar ...
Active profiles: barbaz, foobar
Foo = foo in foobar override properties
Bar = bar in foobar override properties
Baz = bar in barbaz override properties
判决:很明显,最后一个赢了!
哦,还有:非覆盖属性合并到一个大的快乐属性集(这就是我来这里搜索的原因)