使用@ConfigurationProperties注解
配置文件
person:
#注入普通屬性
lastName: zhangsan
age: 18
birth: 1995/07/09
boss: true
#map
maps: {key1: v1, key2: v2}
#list
lists: [1,2,a,b]
#對象
dog:
name: xiaohua
age: 3
javabean
package com.xun.springboot_config.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @program:
* @description:
* @author: 尋牲阁。
* @create: 2018-06-05 22:32
**/
/**
* 將配置文件中的每一個屬性的值映射到這個組件這種
* @ConfigurationProperties:告訴springboot將本類中的所有屬性和配置文件進行綁定
* prefix = "person" 指定配置文件中哪個下面的屬性進行映射
*
* 只有這個組件是容器中的組件醇蝴,才能提供@ConfigurationProperties功能
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Date birth;
private boolean boss;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
get set toString方法省略冗美。。状答。
}
package com.xun.springboot_config.bean;
/**
* @program:
* @description:
* @author: 尋冷守。
* @create: 2018-06-05 22:35
**/
public class Dog {
private String name;
private Integer age;
get set toString方法省略。惊科。拍摇。
}
使用springboot測試方法進行測試
package com.xun.springboot_config;
import com.xun.springboot_config.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootConfigApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}
測試結果:
Person{lastName='zhangsan', age=18, birth=Sun Jul 09 00:00:00 CST 1995, boss=true, maps={key1=v1, key2=v2}, lists=[1, 2, a, b], dog=Dog{name='xiaohua', age=3}}
使用@Value注解注入
@Component
public class Person {
//只支持簡單類型封裝
@Value("${person.lastName}")
private String lastName;
private Integer age;
private Date birth;
private boolean boss;
//不支持復雜類型封裝
@Value("${person.maps}")
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
兩者對比
如果說我們只是在某個業(yè)務中需要獲取一下配置文件中的某項值,使用@Value馆截;
例如:
package com.xun.springboot_config.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @program:
* @description:
* @author: 尋充活。
* @create: 2018-06-05 23:36
**/
@RestController
public class HelloController {
@Value("${person.lastName}")
private String name;
@RequestMapping("hello")
public String sayHello(){
return "hello "+name;
}
}
結果就是:hello zhangsan
如果專門編寫了一個javabean來和配置文件進行映射,我們就直接使用@ConfigurationProperties(并且這個注解支持參數(shù)校驗)