为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Boot属性配置文件&多环境配置

标签:
SpringBoot

Spring Boot属性配置文件&多环境配置


相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷。我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁多的XML配置内容,替代它的是在pom.xml中引入模块化的Starter POMs,其中各个模块都有自己的默认配置,所以如果不是特殊应用场景,就只需要在application.properties中完成一些属性配置就能开启各模块的应用。

在之前的各篇文章中都有提及关于application.properties的使用,主要用来配置数据库连接、日志相关配置等。除了这些配置内容之外,本文将具体介绍一些在application.properties配置中的其他特性和使用方法。

自定义属性与加载

我们在使用Spring Boot的时候,通常也需要定义一些自己使用的属性,我们可以如下方式直接定义:

com.didispace.blog.name=itzzy
com.didispace.blog.title=Spring Boot学习

然后通过@Value("${属性名}")注解来加载对应的配置属性,具体如下:

@Componentpublic class BlogProperties {    @Value("${com.didispace.blog.name}")    private String name;    @Value("${com.didispace.blog.title}")    private String title;    // 省略getter和setter}

按照惯例,通过单元测试来验证BlogProperties中的属性是否已经根据配置文件加载了。

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class ApplicationTests {    @Autowired
    private BlogProperties blogProperties;    @Test
    public void getHello() throws Exception {
        Assert.assertEquals(blogProperties.getName(), "itzzy");
        Assert.assertEquals(blogProperties.getTitle(), "Spring Boot学习");
    }

}

参数间的引用

在application.properties中的各个参数之间也可以直接引用来使用,就像下面的设置:

com.didispace.blog.name=itzzy
com.didispace.blog.title=Spring Boot学习
com.didispace.blog.desc=${https://www.jianshu.com/u/55170d24f9a6}正在努力写《${https://www.jianshu.com/u/55170d24f9a6.title}》

https://www.jianshu.com/u/55170d24f9a6
参数引用了上文中定义的name和title属性,最后该属性的值就是itzzy正在努力写《Spring Boot学习》。

使用随机数

在一些情况下,有些参数我们需要希望它不是一个固定的值,比如密钥、服务端口等。Spring Boot的属性配置文件中可以通过${random}来产生int值、long值或者string字符串,来支持属性的随机值。

# 随机字符串com.didispace.blog.value=${random.value}# 随机intcom.didispace.blog.number=${random.int}# 随机longcom.didispace.blog.bignumber=${random.long}# 10以内的随机数com.didispace.blog.test1=${random.int(10)}# 10-20的随机数com.didispace.blog.test2=${random.int[10,20]}

通过命令行设置属性值

相信使用过一段时间Spring Boot的用户,一定知道这条命令:java -jar xxx.jar --server.port=8888,通过使用–server.port属性来设置xxx.jar应用的端口为8888。

在命令行运行时,连续的两个减号--就是对application.properties中的属性值进行赋值的标识。所以,java -jar xxx.jar --server.port=8888命令,等价于我们在application.properties中添加属性server.port=8888,该设置在样例工程中可见,读者可通过删除该值或使用命令行来设置该值来验证。

通过命令行来修改属性值固然提供了不错的便利性,但是通过命令行就能更改应用运行的参数,那岂不是很不安全?是的,所以Spring Boot也贴心的提供了屏蔽命令行访问属性的设置,只需要这句设置就能屏蔽:SpringApplication.setAddCommandLineProperties(false)。

多环境配置

我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。

对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot也不例外,或者说更加简单。

  • 1.在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境

  • application-test.properties:测试环境

  • application-prod.properties:生产环境

application-dev.properties# 服务端口server.port=1111#可以定义一些自己使用的属性,然后通过@Value("${属性名}}")注解来加载对应的配置属性com.didispace.blog.name=程序猿DD
com.didispace.blog.title=Spring Boot教程
com.didispace.blog.desc=${com.didispace.blog.name}正在努力写《${com.didispace.blog.title}》# 随机字符串com.didispace.blog.value=${random.value}# 随机intcom.didispace.blog.number=${random.int}# 随机longcom.didispace.blog.bignumber=${random.long}# 10以内的随机数com.didispace.blog.test1=${random.int(10)}# 10-20的随机数com.didispace.blog.test2=${random.int[10,20]}## 多环境配置文件激活属性#spring.profiles.active=dev

webp

dev

至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

如:spring.profiles.active=test就会加载application-test.properties配置文件内容

下面,以不同环境配置不同的服务端口为例,进行样例实验。

  • 针对各环境新建不同的配置文件application-dev.properties、application-test.properties、application-prod.properties

  • 在这三个文件均都设置不同的server.port属性,如:dev环境设置为1111,test环境设置为2222,prod环境设置为3333

  • application.properties中设置spring.profiles.active=dev,就是说默认以dev环境设置

  • 测试不同配置的加载

    • 执行java -jar xxx.jar,可以观察到服务端口被设置为1111,也就是默认的开发环境(dev)

    Chapter2-1-1 git:(master)  java -jar /Users/zzy/Documents/zzy/code_github/SpringBoot-Learning/Chapter2-1-1/target/Chapter2-1-1-1.0.0.jar

2018-08-21 15:47:13.389  INFO 38904 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-08-21 15:47:13.491  INFO 38904 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 1111 (http)
2018-08-21 15:47:13.495  INFO 38904 --- [           main] com.didispace.Application                : Started Application in 3.044 seconds (JVM running for 3.438)
注意端口!访问hello接口
    @RestControllerpublic class HelloController {    @RequestMapping("/hello")    public String index() {        return "Hello World";
    }
- 执行java -jar xxx.jar --spring.profiles.active=test,可以观察到服务端口被设置为2222,也就是测试环境的配置(test)
  Chapter2-1-1 git:(master)  java -jar /Users/zzy/Documents/zzy/code_github/SpringBoot-Learning/Chapter2-1-1/target/Chapter2-1-1-1.0.0.jar  --spring.profiles.active=test2018-08-21 15:50:48.710  INFO 38940 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-08-21 15:50:48.797  INFO 38940 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 2222 (http)
2018-08-21 15:50:48.801  INFO 38940 --- [           main] com.didispace.Application                : Started Application in 2.674 seconds (JVM running for 3.072)

webp

test

- 执行java -jar xxx.jar --spring.profiles.active=prod,可以观察到服务端口被设置为3333,也就是生产环境的配置(prod)
  Chapter2-1-1 git:(master)  java -jar /Users/zzy/Documents/zzy/code_github/SpringBoot-Learning/Chapter2-1-1/target/Chapter2-1-1-1.0.0.jar  --spring.profiles.active=prod

2018-08-21 15:52:21.029  INFO 38949 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-08-21 15:52:21.118  INFO 38949 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 3333 (http)
2018-08-21 15:52:21.121  INFO 38949 --- [           main] com.didispace.Application                : Started Application in 2.492 seconds (JVM running for 2.875)

webp

prod

按照上面的实验,可以如下总结多环境的配置思路:

  • application.properties中配置通用内容,并设置spring.profiles.active=dev,以开发环境为默认配置

  • application-{profile}.properties中配置各个环境不同的内容

  • 通过命令行方式去激活不同环境的配置

  • 2.创建profiles目录

webp

profiles

  • 创建不同环境下的配置文件

application-dev.yml、application-test.yml、application-prod.yml或者application-dev.properties、application-test.properties、application-prod.properties
- pom.xml文件中配置profiles节点

<profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <profileActive>dev</profileActive>
            </properties>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/profiles/dev</directory>
                    </resource>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <profileActive>test</profileActive>
            </properties>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/profiles/test</directory>
                    </resource>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <profileActive>prod</profileActive>
            </properties>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/profiles/prod</directory>
                    </resource>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
    </profiles>
  • 使用maven命令打包成相应环境的程序包

    1.生产环境

mvn clean package -Pprod -U  
# 或者mvn clean package -DprofileActive=prod -U
2.测试环境
mvn clean package -Ptest -U  
# 或者mvn clean package -DprofileActive=test -U
3.开发环境
mvn clean package -Pdev -U  
# 或者mvn clean package -DprofileActive=dev -U
  Chapter2-1-1 git:(master)  mvn clean compile package -Pdev -Dmaven.test.skip=true  -U

  Chapter2-1-1 git:(master)  java -jar target/Chapter2-1-1-1.0.0.jar                   


2018-08-21 16:39:49.285  INFO 39791 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-08-21 16:39:49.380  INFO 39791 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 1111 (http)
2018-08-21 16:39:49.385  INFO 39791 --- [           main] com.didispace.Application                : Started Application in 2.811 seconds (JVM running for 3.175)

访问hello接口


webp

dev

项目结构

webp

@Componentpublic class BlogProperties {

    @Value("${com.didispace.blog.name}")    private String name;
    @Value("${com.didispace.blog.title}")    private String title;
    @Value("${com.didispace.blog.desc}")    private String desc;

    @Value("${com.didispace.blog.value}")    private String value;
    @Value("${com.didispace.blog.number}")    private Integer number;
    @Value("${com.didispace.blog.bignumber}")    private Long bignumber;
    @Value("${com.didispace.blog.test1}")    private Integer test1;
    @Value("${com.didispace.blog.test2}")    private Integer test2;    public String getName() {        return name;
    }    public void setName(String name) {        this.name = name;
    }    public String getTitle() {        return title;
    }    public void setTitle(String title) {        this.title = title;
    }    public String getDesc() {        return desc;
    }    public void setDesc(String desc) {        this.desc = desc;
    }    public String getValue() {        return value;
    }    public void setValue(String value) {        this.value = value;
    }    public Integer getNumber() {        return number;
    }    public void setNumber(Integer number) {        this.number = number;
    }    public Long getBignumber() {        return bignumber;
    }    public void setBignumber(Long bignumber) {        this.bignumber = bignumber;
    }    public Integer getTest1() {        return test1;
    }    public void setTest1(Integer test1) {        this.test1 = test1;
    }    public Integer getTest2() {        return test2;
    }    public void setTest2(Integer test2) {        this.test2 = test2;
    }
}


@RestControllerpublic class HelloController {

    @RequestMapping("/hello")    public String index() {        return "Hello World";
    }

}

@SpringBootApplicationpublic class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}

# 服务端口
server.port=1111#可以定义一些自己使用的属性,然后通过@Value("${属性名}}")注解来加载对应的配置属性
com.didispace.blog.name=itzzy
com.didispace.blog.title=Spring Boot学习
com.didispace.blog.desc=${com.didispace.blog.name}正在努力写《${com.didispace.blog.title}》

# 随机字符串
com.didispace.blog.value=${random.value}
# 随机intcom.didispace.blog.number=${random.int}
# 随机longcom.didispace.blog.bignumber=${random.long}
# 10以内的随机数
com.didispace.blog.test1=${random.int(10)}
# 10-20的随机数
com.didispace.blog.test2=${random.int[10,20]}

## 多环境配置文件激活属性
#spring.profiles.active=dev



作者:it_zzy
链接:https://www.jianshu.com/p/f24b312db08b


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消