以前在工作中总是不明白spring是如何区分不同环境的,今天写了一个简单的小demo,明白了。记录一下,以备自己以后独立开发项目使用。

首先应该在pom.xml中添加以下配置:

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78


   <profiles>


        <profile>


            <!-- 生产环境 -->


            <id>prod</id>


            <properties>


                <profiles.active>prod</profiles.active>


            </properties>


        </profile>


        <profile>


            <!-- 本地开发环境 -->


            <id>dev</id>


            <properties>


                <profiles.active>dev</profiles.active> 


            </properties>


            <activation>


                <activeByDefault>true</activeByDefault>


            </activation>


        </profile>


        <profile>


            <!-- 测试环境 -->


            <id>test</id>


            <properties>


                <profiles.active>test</profiles.active>


            </properties>


        </profile>


    </profiles>

其次根据pom中三种不同环境分别创建3个配置文件,分别为

1
2
3
4
5
6
7
8
9


application-dev.properties


application-test.properties


application-prod.properties

最后在application.properties中,读取

1
2
3


spring.profiles.active=@profiles.active@

注:@profiles.active@ 要与pom中的标签保持一致,否则会报错

这样就实现了不同环境配置的切换。

打包的时候可以在IDEA中MAVEN插件那勾选对应的环境

或者命令行打包带上对应的参数

yml配置文件是我们在真实工作中经常会使用的配置文件的格式,有时候我们会遇到些我们没有遇到过的新的表现形式。下面我将会谈谈我在工作中遇到的一个日志配置文件比较有意思的表现形式:

spring.profiles.active=@profiles.active@的含义

spring.profiles.active=@profiles.active@ ,其实是配合 maven profile进行选择不同配置文件进行启动。

当执行mvn clean package -P test命令时, @profiles.active@ 会替换成 test

打开 jar包,即可看到测试包打包完成

生产环境包

1
2
3


mvn clean package -P prod

开发环境包

1
2
3


mvn clean package -P dev

测试环境包

1
2
3


mvn clean package -P test