如何在SpringBootTest中启用不同的profiles

实现步骤

  • 测试类标注@ActiveProfiles(resolver = ProfilesResolver.class)
  • 自定义类 ProfilesResolver 实现接口 ActiveProfilesResolver,并实现接口中唯一的方法resolve(Class<?> targetClass)
  • maven-surefire-plugin 插件中配置
    1
    2
    3
     <systemPropertyVariables>
    <spring.profiles.active>${spring.profiles.active}</spring.profiles.active>
    </systemPropertyVariables>

实现如下:

1. 标注启用

1
2
3
4
5
6
7
8
9
10
11
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PetstoreApp.class}, // 我们的 application 名为 PetstoreApp
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(resolver = ProfilesResolver.class)
public abstract class BaseResourceTest {
@BeforeClass
public static void setUp() {
String activeProfiles = System.getProperty("spring.profiles.active");
System.out.println(String.format("Resource Tests resolved profiles are [%s]", activeProfiles));
}
}

这个类存在的意义就是为了让其它类别的 ResourceTest 继承它,并在一次启动当中运行完所有的集成测试。避免每个 ResourceTest 都初始化启动 Application,造成运行速度变慢。

注意abstract关键字
如果不使用abstract关键字,那么maven-surefire-plugin就会抛出如下错误:

Tests in error:
BaseResourceTest.initializationError » No runnable methods

2. 实现自定义类 ProfilesResolver,如下:

1
2
3
4
5
6
7
8
9
10
import org.springframework.test.context.ActiveProfilesResolver;

public class ProfilesResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> aClass) {
String activeProfiles = System.getProperty("spring.profiles.active");

return new String[] {activeProfiles != null ? activeProfiles : "local"};
}
}

这里表示我们会从系统变量当中读取spring.profiles.active,但是这个变量从什么地方来呢?
我首先想到的是 maven 的 profiles 中设置 properties,如下:

1
2
3
4
5
6
<profile>
<id>local</id>
<properties>
<spring.profiles.active>local</spring.profiles.active>
</properties>
</profile>

如此,当我们在命令行中运行mvn test -Plocal的时候,就表明启用了 local 这个 profile。相应地,在 maven 的上下文当中,spring.profiles.active变量的值就是local

但是运行测试的时候,我们 ProfilesResolver 中的 System.getProperty("spring.profiles.active")返回的始终是null。其实道理很简单,maven 中定义的 properties 全是给 maven 自己(包含各类插件)用的,它并不会传递给应用程序使用。

注意:


properties 中定义的 spring.profiles.active 其实主要是给插件 maven-resources-plugin 使用的,具体请参看备注。


3. 定义systemPropertyVariables

所以我们需要定义systemPropertyVariables,顾名思义,这是系统变量的定义,在应用程序中就可以使用System.getProperty("spring.profiles.active")获得。

放在哪里合适呢?跑测试的插件中最合适!

所以,我们有如下的配置:

1
2
3
4
5
6
7
8
9
10
11
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<runOrder>alphabetical</runOrder>
<systemPropertyVariables>
<spring.profiles.active>${spring.profiles.active}</spring.profiles.active>
</systemPropertyVariables>
</configuration>
</plugin>

结合上面 properties 的配置,当我们再次运行mvn test -Plocal的时候,就会得到一个名为spring.profiles.active的系统变量,它的值由${spring.profiles.active}决定。此处,就是local。


备注

properties 中 spring.profiles.active 的另外用途
只要 maven 的 properties 中定义了 spring.profiles.active ,运行mvn spring-boot:run -Plocal的时候,spring boot 就会启用applicaiton-local.yml profile 文件。

为什么会这样的呢?按常理推断,应该是spring-boot-maven-plugin的配置项自动读取了我们设置的 properties spring.profiles.active,但是只要看一眼这个插件的文档就会发现,除非显式地在插件的configuration下配置了profiles参数或者手动传入run.profiles系统变量example,否则插件本身(可以像我一样扫一眼插件的源码)并无法感知到底启用 spring 的哪个 profile!所以这个假设不成立。

答案在bootstrap.yml当中!
以下是resources/config/bootstrap.yml中的内容

1
2
3
4
5
6
7
8
9
spring:
application:
name: petstore
profiles:
# The commented value for `active` can be replaced with valid Spring profiles to load.
# *注意底下这句话*
# Otherwise, it will be filled in by maven when building the WAR file
# Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS`
active: #spring.profiles.active#

这里的注释很有用,明确地告诉我们在构建 WAR 包的时候,maven 会帮我们把#spring.profiles.active#替换成真正的值。

这又是怎么做到的呢?一切归功于maven-resources-plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
<executions>
<execution>
<id>default-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target/classes</outputDirectory>
<useDefaultDelimiters>false</useDefaultDelimiters>
<delimiters>
<delimiter>#</delimiter> <!-- 看这里 -->
</delimiters>
<resources>
<resource>
<directory>src/main/resources/</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources/</directory>
<filtering>false</filtering>
<excludes>
<exclude>**/*.xml</exclude>
<exclude>**/*.yml</exclude>
</excludes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>

这个插件除了简单的 copy 功能之外,还能进行 Filtering 操作

Filtering
Variables can be included in your resources. These variables, denoted by the ${…} delimiters, can come from the system properties, your project properties, from your filter resources and from the command line.

大意是说,你可以在 resources 文件定义自己的变量,这些变量可以来自系统属性、maven 工程属性,你过滤的 resources 文件和命令行。

说白了,就是在 copy 资源文件的时候,同时帮你把文件中的变量(占位符)替换成真实的值。而这里就是通过<delimiter>#</delimiter>来规定变量格式的!换句话说,在文件中只要是以#开头和结尾的字符串都会被替换掉(变量有定义的情况下;否则保持原样)。

这里,由于绑定了生命周期——validate,可以直接运行mvn validate -Plocal这样的命令进行快速验证。得到的bootstrap.yml内容如下:

1
2
3
4
5
6
7
8
spring:
application:
name: petstore
profiles:
# The commented value for `active` can be replaced with valid Spring profiles to load.
# Otherwise, it will be filled in by maven when building the WAR file
# Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS`
active: dev # 替换成功

回到最开始的疑问,为什么只要 maven 的 properties 中定义了 spring.profiles.active ,运行mvn spring-boot:run -Plocal的时候,就可以spring boot 就会启用applicaiton-local.yml profile 文件呢?

因为,maven 在运行命令之前已经做了 copy-resources 的操作,那时候就已经把bootstrap.yml中的spring.profiles.active替换成 local 了,所以启动 springboot application 的时候,它会启用spring.profiles.active代表的值,此处就是 local,那么启用的文件自然就是application-local.yml