Spring的配置文件功能,以及Spring Boot的application.properties
春天的个人资料功能
配置文件是DI容器中的Bean组。可以指定任意的组名。
要为Bean指定配置文件,请使用@Profile注解。
@Profile("dev")
@Component
public class DevBean {
}
@Profile("production")
@Component
public class ProductionBean {
}
没有添加@Profile注解的Bean不属于任何特定的配置文件(也被称为默认配置文件)。没有配置文件的Bean在运行时无论指定任何配置文件都会始终有效。
@Component
public class DefaultBean {
}
指定多个配置文件
@Profile的值元素是一个数组,所以可以为一个Bean指定多个配置文件。如果指定了多个配置文件,则在运行时指定任何一个配置文件时都将被激活(不需要指定全部配置文件)。
@Profile({"profile1", "profile2"})
@Component
public class FooBean {
}
使用逻辑运算符
你可以使用否定符号(!)、与符号(&)、或符号(|)来表达这个意思。
@Profile("!profile1")
@Component
public class FooBean {
}
@Profile("profile1 & profile2")
@Component
public class FooBean {
}
@Profile("profile1 | profile2")
@Component
public class FooBean {
}
如果存在 & 和 | 混合的情况,必须使用圆括号 ()。
❌ @Profile(“profile1 | profile2 & profile3”)
⭕ @Profile(“profile1 | (profile2 & profile3)”)
在运行时指定配置文件。
在运行时,有很多种方法可以指定使用该配置文件!最常用的有以下三种。优先级从上到下逐渐增高。
-
- 在JUnit测试类上添加@ActiveProfiles(“profile name”)
多个profile指定时,使用数组指定@ActiveProfiles({“profile1”, “profile2”})
在java命令中添加-Dspring.profiles.active=profile name
多个profile指定时,使用逗号分隔-Dspring.profiles.active=profile1,profile2
通过环境变量SPRING_PROFILES_ACTIVE指定profile name
多个profile指定时,使用逗号分隔SPRING_PROFILES_ACTIVE=profile1,profile2
如前所述,最重要的注意事项是,无论在执行时指定了哪个配置文件,没有配置文件的Bean都将始终被使用。
Spring Boot的application.properties文件
在使用Spring Boot时,可以利用配置文件application.properties和配置文件中的配置文件。application.properties是没有配置文件的,application-配置文件名.properties是仅在指定配置文件时使用的配置。
换句话说,无论指定了哪个配置文件,都会使用在application.properties中写的设置。
在指定了配置文件的情况下,如果在application.properties和application-配置文件名.properties中存在同名的属性,则后者的值将被优先选择(=覆盖)。
sample.value1=Default1
sample.value2=Default2
# devプロファイル指定時はこちらの値が使われる
sample.value1=Dev1
使用Spring Boot时的运行时配置文件指定。
如果使用Spring Boot,除了上述的指定方法,还可以通过命令行参数来指定。
$ java -jar target/spring-boot-profiles-sample-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
对于IntelliJ IDEA(仅适用于Ultimate版),您可以在运行配置中指定(在运行时通过-D添加)。

示例代码
请参阅相关资料。
-
- Spring Reference Documentation – Core Technologies
- Spring Boot reference Documentation – 4.2. Externalized Configuration