Spring Boot 揭秘与实战 关于配置文件有哪些很棒的特性
Spring 框架本身提供了多种的方式来管理配置属性文件。Spring 3.1 之前可以使用 PropertyPlaceholderConfigurer。Spring 3.1 引入了新的环境(Environment)和概要信息(Profile)API,是一种更加灵活的处理不同环境和配置文件的方式。不过 Spring 这些配置管理方式的问题在于选择太多,让开发人员无所适从。Spring Boot 提供了一种统一的方式来管理应用的配置。
使用属性文件
自定义属性
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; @Testpublic void test1() throws Exception { System.out.println("real_name : " + realname); System.out.println("nick_name : " + nickname);}
参数引用
此外,我们来可以通过引用参数来使用。
author.product=Spring Boot 揭秘与实战author.project=springboot-actionauthor.intro=${author.product} | ${author.project} | 作者:${author.realname}
那么,问题来了, author.intro 通过参数引用得到的结果是什么呢?现在,通过单元测试用例来进行测试。
@Value("${author.intro}")private String intro; @Testpublic 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; @Testpublic 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; @Testpublic void test4() throws Exception { System.out.println("email : " + email); System.out.println("blog : " + blog);}
更多相关文章
- 人手一套Linux环境之:Windows版本教程
- 多线程环境下生成随机数
- Linux环境都没有,怎么学编程?憋说了,肝!(保姆级教程)
- jQuery——将title属性用作悬停的文本,但只在同一父类中使用。
- jQuery编程基础精华02(属性、表单过滤器,元素的each,表单选择器,子元
- Google地图信息窗口左箭头,右箭头传递TypeError:无法读取未定义的
- 3.29 学前端 jquery之操作元素之属性操作
- 获取复选框的文本属性
- 将JSON结果返回给ajax请求的MVC ErrorHandling属性仅适用于local