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