使用如下三个注解:
-
@Configuration
-
@PropertySource(value=“classpath:application.yml”)
指明了配置文件所处的位置,classpath 下的 application.yml。
-
@ConfigurationProperties(prefix=“com.springboot”)
指明要加载配置文件中的那个前缀下的属性,因为配置文件中一般配有多个不同类型的属性,用不同的前缀来区分。
application.yml 配置文件内容如下:
com.springboot:
name: hello_yml
age: 12
num: ${random.int}
max: ${random.int(10)}
value: ${random.value}
注:yml 文件中不要用 [Tab] 键!否则,启动时会报错。层级关系用空格隔开即可,数量不限,同一层级的要对齐,冒号后面如果跟属性值,要有一个空格,否则会报错。
对应的实体类:
package com.qjl.bootstart.yml;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value="classpath:application.yml")
@ConfigurationProperties(prefix="com.springboot")
public class YmlUtil {
private String name;
private Integer age;
private Integer num;
private Integer max;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getMax() {
return max;
}
public void setMax(Integer max) {
this.max = max;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
注:实体类对应的属性名要与配置文件中的属性保持一致,并且要加上 setter 和 getter 方法。
这样在项目启动的时候,SpringBoot 就会去加载对应配置文件中的属性,反射创建一个 bean 对象,并放入 Spring 的容器(ConcurrentHashMap)中,在需要使用的地方用 @Autowired 属性注入。
比方说,我们要在 Controller 中注入这个实体类,只需要像下面这样做:
package com.qjl.bootstart.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qjl.bootstart.yml.YmlUtil;
/**
* 类名称:SpringMVC的控制器
* 全限定性类名: com.qjl.bootstart.controller.BootController
* @author 曲健磊
* @date 2018年8月4日上午10:38:23
* @version V1.0
*/
@RestController
@RequestMapping("/boot")
@EnableConfigurationProperties(value={YmlUtil.class}) // 使用配置
public class BootController {
@Autowired
private YmlUtil util;
@RequestMapping("/random")
public String testRandom() {
StringBuffer buffer = new StringBuffer();
buffer.append("hello SrpingBoot random<br />");
buffer.append("[").append(util.getName()).append("]<br />");
return buffer.toString();
}
}