Spring Boot 揭秘与实战(四) 配置文件篇 - 有哪些很棒的特性

2,179 阅读2分钟

Spring 框架本身提供了多种的方式来管理配置属性文件。Spring 3.1 之前可以使用 PropertyPlaceholderConfigurer。Spring 3.1 引入了新的环境(Environment)和概要信息(Profile)API,是一种更加灵活的处理不同环境和配置文件的方式。不过 Spring 这些配置管理方式的问题在于选择太多,让开发人员无所适从。Spring Boot 提供了一种统一的方式来管理应用的配置。
原文地址:Spring Boot 揭秘与实战(四) 配置文件篇 - 有哪些很棒的特性
博客地址:blog.720ui.com/

使用属性文件

自定义属性

Spring Boot 提供的 SpringApplication 类会搜索并加载 application.properties 文件来获取配置属性值。

创建 application.properties 文件。

author.realname=梁桂钊
author.nickname=LiangGzone

不需要其他配置,我们只需要通过 @Value("${属性名}") 注解来加载对应的配置属性,现在,通过单元测试用例来验证吧。

@Value("${author.realname}")
private String realname;

@Value("${author.nickname}")
private String nickname;

@Test
public void test1() throws Exception {
    System.out.println("real_name : " + realname);
    System.out.println("nick_name : " + nickname);
}

参数引用

此外,我们来可以通过引用参数来使用。

author.product=Spring Boot 揭秘与实战
author.project=springboot-action
author.intro=${author.product} | ${author.project} | 作者:${author.realname}

那么,问题来了, author.intro 通过参数引用得到的结果是什么呢?现在,通过单元测试用例来进行测试。

@Value("${author.intro}")
private String intro;

@Test
public void test2() throws Exception {
    System.out.println("intro : " + intro);
}

随机数属性

Spring Boot 的属性配置文件中 ${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。

# 32位随机字符串
rand.str = ${random.value}
# 随机int类型
rand.intid = ${random.int}
# 随机long类型
rand.longid = ${random.long}
# 100以内的随机int类型
rand.number = ${random.int(100)}
# 0-100范围内的随机int类型
rand.range = ${random.int[0,100]}

附上,单元测试用例。

@Value("${rand.str}")
private String randStr;
@Value("${rand.intid}")
private int randIntid;
@Value("${rand.longid}")
private long randLongid;
@Value("${rand.number}")
private int randNumber;
@Value("${rand.range}")
private String randRange;

@Test
public void test3() throws Exception {
    System.out.println("rand.str : " + randStr);
    System.out.println("rand.intid : " + randIntid);
    System.out.println("rand.longid : " + randLongid);
    System.out.println("rand.number : " + randNumber);
    System.out.println("rand.range : " + randRange);
}

application-{profile}.properties参数加载

一个非常典型的场景,多环境配置。Spring Boot 也给我们提供了非常简化的配置。

现在,我们根据环境创建4个配置文件。

#开发环境
application-development.properties

#测试环境
application-test.properties

#预生产环境
application-preproduction.properties

#生产环境
application-product.properties

执行命令,通过 active 加载测试环境的配置。

java -jar  ***.jar  --spring.profiles.active=test

YAML文件

相对于属性文件,YAML 文件是一个更好的配置文件格式。Spring Boot 提供的 SpringApplication 类也提供了对 YAML 配置文件的支持。
创建application.yml 文件

author:
 email: lianggzone@163.com
 blog: http://blog.720ui.com

那么,我们再来测试一下,是否正常使用哈。

@Value("${author.email}")
private String email;
@Value("${author.blog}")
private String blog;

@Test
public void test4() throws Exception {
    System.out.println("email : " + email);
    System.out.println("blog : " + blog);
}

源代码

相关示例完整代码: springboot-action

(完)

更多精彩文章,尽在「服务端思维」微信公众号!