下面是需要注入属性的类
package com.springboot.bean;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;import java.util.Date;
import java.util.List;
import java.util.Map;//后面会在配置类中使用@EnableConfigurationProperties注解,如果是用该注解,则不需要将该属性类上添加@Component注解
//@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {private String lastName;private int age;private Boolean boss;private Date birth;private Map<String,Object> maps;private List<Object> lists;private Dog dog;}
package com.springboot.bean;import lombok.Data;@Data
public class Dog {private String name;private int age;}
yal文件
person:lastname: liqingfengage: 23boss: falsebirth: 1995/10/04maps: {k1: v1,k2: v2}lists:- list1- list2dog:name: 小狗age: 2
下面是在properties文件中的写法
person.last-name=guoanni
person.age=25
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=金毛
person.dog.age=4
配置类
@Configuration
@EnableSwagger2
//显式的指定具体的Properties类,不通过扫描的方式,更清晰;
//另也不需要在@ConfigurationProperties注解的自定义Properties类上加@Component
@EnableConfigurationProperties(value = {Person.class
})
public class SpringBootConfiguration {}
这里需要额外说一个东西,是springboot提供的一个maven依赖,可以自动将yml文件中属性和属性类进行关联,可以有提示,避免在yml文件中写错,只需要将该依赖添加到pom文件中就可以了
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>