前言

分散配置是系统必不可少的一部分,将配置参数抽离出来为后期维护提供很大的便利。spring boot 默认支持两个格式的配置文件:.properties .yml。

.properties与.yml

*.properties属性文件;属于最常见的一种; 
*.yml是yaml格式的文件,yaml是一种非常简洁的标记语言。

在*.properties中定义user.address.stree=hangzhou等价与yaml文件中的

   user:address: stree:hangzhou

从上可以发现yaml层次感更强,具体在项目中选择那种资源文件是没有什么规定的。

spring boot配置

简单案例

首先在类路径下创建application.properties文件并定义 
name=liaokailin

创建一个beanUser.java

@Component
public class User {private @Value("${name:lkl}") String name;public String getName() {return name;}public void setName(String name) {this.name = name;}

在 HelloWorldController.java调用对应bean

package com.lkl.springboot.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import com.lkl.springboot.config.User;
import com.lkl.springboot.event.CallEventDemo;@RestController
@RequestMapping("/springboot")
public class HelloWorldController {@AutowiredCallEventDemo callEventDemo;@AutowiredUser          user;@RequestMapping(value = "/{name}", method = RequestMethod.GET)@ResponseBodypublic String sayWorld(@PathVariable("name") String name) {System.out.println("userName:" + user.getName()); return "Hello " + name;}}

启动该spring boot工程,在命令行执行

curl http://localhost:8080/springboot/liaokailin 
控制台成功输出name对应值

解析

  • 在spring boot中默认会加载 
    classpath:/,classpath:/config/,file:./,file:./config/ 路径下以application命名的property或yaml文件;
  • 参数spring.config.location设置配置文件存放位置
  • 参数spring.config.name设置配置文件名称

配置文件获取随机数

在spring boot配置文件中可调用Random中方法

application.properties中为user增加age参数 age=${random.int}

name=liaokailin
age=${random.int}

bean中同时增加参数

@Component
public class User {private @Value("${name:lkl}") String name;private @Value("${age}") Integer     age;//getter and setter and toString()

在启动工程时会为age随机生成一个值

${random.int(100)} : 限制生成的数字小于10
${random.int[0,100]} : 指定范围的数字

在配置文件调用占位符

修改配置文件:

userName=liaokailin
age=${random.int[0,100]}
remark=hello,my name is ${userName},age is ${age}

修改bean:

@Component
public class User {private @Value("${userName:lkl}") String name;private @Value("${age}") Integer         age;private @Value("${remark}") String       remark;

执行发现remark答应出:

remark=hello,my name is liaokailin,age is 25

可以发现将name修改为userName,在配置文件中调用${name}是工程名。

去掉@Value

大家可以发现前面在bean中调用配置参数使用的为注解@Value,在spring boot中是可以省去该注解。

配置文件:

userName=liaokailin
age=${random.int[0,100]}
remark=hello,my name is ${userName},age is ${age}
user.address=china,hangzhou

增加user.address=china,hangzhou,为了调用该参数来使用@ConfigurationProperties

User.java

@Component
@ConfigurationProperties(prefix = "user")
public class User {private @Value("${userName:lkl}") String name;private @Value("${age}") Integer         age;private @Value("${remark}") String       remark;private String                           address;

使用@ConfigurationProperties需要指定prefix,同时bean中的属性和配置参数名保持一致。

实体嵌套配置

在User中定义一个Address实体同样可以快捷配置

User.java

@Component
@ConfigurationProperties(prefix = "user")
public class User {private @Value("${userName:lkl}") String name;private @Value("${age}") Integer         age;private @Value("${remark}") String       remark;private String                           address;private Address                          detailAddress;

Address.java

public class Address {

private String country;
private String province;
private String city;
...

application.properties`

userName=liaokailin
age=${random.int[0,100]}
remark=hello,my name is ${userName},age is ${age}
user.address=china,hangzhou
user.detailAddress.country=china
user.detailAddress.province=zhejiang
user.detailAddress.city=hangzhou

运行得到

userUser [name=liaokailin, age=57, remark=hello,my name is liaokailin,age is 0, address=china,hangzhou, detailAddress=Address [country=china, province=zhejiang, city=hangzhou]]

这种嵌套关系如果通过yaml文件展示出来层次感会更强。

user:detailAddress:country:chinaprovince:zhejiangcity:hangzhou

注意在yaml中缩进不要使用TAB

配置集合

一个人可能有多个联系地址,那么地址为集合

User.java

 @Component
@ConfigurationProperties(prefix = "user")
public class User {private @Value("${userName:lkl}") String name;private @Value("${age}") Integer         age;private @Value("${remark}") String       remark;private String                           address;private Address                          detailAddress;private List<Address>                    allAddress = new ArrayList<Address>();

application.properties

user.allAddress[0].country=china
user.allAddress[0].province=zhejiang
user.allAddress[0].city=hangzhouuser.allAddress[1].country=china
user.allAddress[1].province=anhui
user.allAddress[1].city=anqing

```

通过`下标`表明对应记录为集合中第几条数据,得到结果:

userUser [name=liaokailin, age=64, remark=hello,my name is liaokailin,age is 82, address=china,hangzhou, detailAddress=Address [country=china, province=zhejiang, city=hangzhou], allAddress=[Address [country=china, province=zhejiang, city=hangzhou], Address [country=china, province=anhui, city=anqing]]]

如果用yaml文件表示为:

application.yml

user:-allAddress:country:chinaprovince:zhejiangcity:hangzhou-allAddress:country:chinaprovince:anhuicity:anqing

多配置文件

spring boot设置多配置文件很简单,可以在bean上使用注解@Profile("development")即调用application-development.properties|yml文件,也可以调用SpringApplication中的etAdditionalProfiles()方法。

例如:

package com.lkl.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;import com.lkl.springboot.listener.MyApplicationStartedEventListener;@Profile("development")
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication app = new SpringApplication(Application.class);//   app.setAdditionalProfiles("development");app.addListeners(new MyApplicationStartedEventListener());app.run(args);}
}

也可以通过启动时指定参数spring.profiles.active

题外话

在实际项目中最好是将配置参数抽离出来集中管理,比如利用淘宝的super-diamond ,consul,zk 等。

spring boot实战(第四篇)分散配置相关推荐

  1. spring boot实战(第六篇)加载application资源文件源码分析

    前言 在上一篇中了解了spring配置资源的加载过程,本篇在此基础上学习spring boot如何默认加载application.xml等文件信息的. ConfigFileApplicationLis ...

  2. spring之旅第四篇-注解配置详解

    spring之旅第四篇-注解配置详解 一.引言 最近因为找工作,导致很长时间没有更新,找工作的时候你会明白浪费的时间后面都是要还的,现在的每一点努力,将来也会给你回报的,但行好事,莫问前程!努力总不会 ...

  3. spring boot实战(第七篇)内嵌容器tomcat配置

    spring boot默认web程序启用tomcat内嵌容器tomcat,监听8080端口,servletPath默认为 / 通过需要用到的就是端口.上下文路径的修改,在spring boot中其修改 ...

  4. spring boot实战(第十篇)Spring boot Bean加载源码分析

    前言 前面的文章描述了Application对应Bean的创建,本篇将阐述spring boot中bean的创建过程 refresh 首先来看SpringApplication#run方法中refre ...

  5. Spring Boot:(四)开发Web应用之JSP篇

    Spring Boot:(四)开发Web应用之JSP篇 前言 上一篇介绍了Spring Boot中使用Thymeleaf模板引擎,今天来介绍一下如何使用SpringBoot官方不推荐的jsp,虽然难度 ...

  6. ssm如何支持热部署_最新Spring Boot实战文档推荐:项目搭建+配置+SSM整合

    在Spring Boot项目中,正常来说是不存在XML配置,这是因为Spring Boot不推荐使用XML,注意,排不支持,Spring Boot推荐开发者使用Java配置来搭建框架, Spring ...

  7. springboot做系统所需的软硬件环境_最新Spring Boot实战文档推荐:项目搭建+配置+SSM整合...

    在Spring Boot项目中,正常来说是不存在XML配置,这是因为Spring Boot不推荐使用XML,注意,排不支持,Spring Boot推荐开发者使用Java配置来搭建框架, Spring ...

  8. Spring Boot实战系列《六》:人事管理系统的登录设计

    Spring Boot实战系列<六>:人事管理系统的登录设计 Spring Boot实战系列<六>:人事管理系统的登录设计 1.前言 在上一篇中教大家在IEDA或者eclips ...

  9. spring boot(一):入门篇

    构建微服务:Spring boot 入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框 ...

最新文章

  1. python fsolve_Python-optimize.leastsq()和optimize.fsolve()
  2. 只做好CTR预估远不够,淘宝融合CTR、GMV、收入等多目标有绝招
  3. 4招教你零基础入门Python
  4. 猫哥教你写爬虫 006--条件判断和条件嵌套
  5. IC/FPGA校招笔试题分析(一)
  6. python导入csv文件-python读写csv文件
  7. Announcing Zuul: Edge Service in the Cloud--转
  8. JavaScript中判断是否存在某属性
  9. 2020年数学与计算机科学奖获得者,2020 数学与计算机科学奖 获奖人 —— 彭实戈 - 未来科学大奖...
  10. python11-28笔记(1.6-1.7)
  11. git 图形化工具 GitKraken 的使用 —— 分支的创建与合并
  12. iOS 判断设备型号
  13. 数组指定位置添加元素_访问数组的任意位置元素的性能真的一样?
  14. Android自定义弹窗页面,Android编程实现的自定义弹窗(PopupWindow)功能示例
  15. 去中心化存储的QoS是什么?
  16. 帆软FineBI试用
  17. 前端开发:Promise的使用丨蓄力计划
  18. SQL Server Arithmetic overflow error converting nvarchar to data type numeric
  19. 隐马尔可夫模型(背景介绍)
  20. 金蝶中间件AAS无法访问管理平台提示404

热门文章

  1. Formal Languages and Compilers-LL(1),FIRST and FOLLOW
  2. 华硕P8B-C/2L及其他
  3. 声音的播放——MCI的使用
  4. 【matlab】面积图(area函数的应用)
  5. AWGN和Rayleigh信道下QPSK的误码率分析
  6. Kinect学习(三):获取RGB颜色数据
  7. Android N新特性
  8. c语言求5个数最小公倍数,C语言,求从键盘输入的五个自然数的最小公倍数
  9. (十) 整合spring cloud云架构 - SSO单点登录之OAuth2.0登录认证(1)
  10. 分布式消息规范 OpenMessaging 1.0.0-preview 发布