我必须进行实验来说服自己。
从Spring Initializr创建最简单的Spring Boot应用程序。
然后向资源目录添加3个属性文件(第一个已经存在,但是为空)。
foo=foo in application.properties
bar=bar in application.properties
baz=baz in application.properties
foo=foo in foobar override properties
bar=bar in foobar override 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 then 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
结论:显然,最后一个胜出!
还有一个小细节:未被覆盖的属性会合并成一个大的属性集合(这也是我来搜索这里的原因)。
id="dataSource"
的bean,则该bean的最后一个定义将被使用,因为第一个定义将被最后一个覆盖。spring.profiles.active
中配置文件的顺序实际上并不重要。 - superEb