学会了写yml的配置文件,然后就要学会如何去给Java代码注入配置文件里面的值了
配置文件值注入
首先在yml里面写属性的值
person:
lastName: hello
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: 12}
lists:
‐ lisi
‐ zhaoliu
dog:
name: 小狗
age: 12
然后给javaBean写注解来注入
将配置文件中配置的每一个属性的值,映射到这个组件中
@ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
prefix = "person":配置文件中哪个下面的所有属性进行一一映射
只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
//必须填成邮箱格式,这是@ConfigurationProperties支持的
@Email
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
还可以用Spring的@Value注解来获取全局配置里面的值注入到对象属性中
@Component
//@ConfigurationProperties(prefix = "person")
@Validated
public class Person
{
/*** <bean class="Person">
* <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/# {SpEL}"></property>
* <bean/>
*/
//lastName必须是邮箱格式
//@Email
@Value("${person.last‐name}")
private String lastName;
@Value("#{11*2}")
private Integer age;
@Value("true")
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists; private Dog dog;