spring boot实战(第四篇)分散配置
前言
分散配置是系統必不可少的一部分,將配置參數抽離出來為后期維護提供很大的便利。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`
?
?
?
運行得到
?
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实战(第四篇)分散配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring boot实战(第二篇)事件
- 下一篇: spring boot实战(第六篇)加载