准备阶段
person:
lastName: zhangsan
email: xxx@163.com
age: 18
birth: 2019/1/10
maps: {k1: v1,k2: v2}
lists:
- lisi
- zhaoliu
pets:
name: 小狗
age: 12
- pom.xml添加依赖【用文件处理器,用于和配置文件进行绑定及字段提示】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 启用IDEA配置

方式一:@Value(“${xxx}”) 注解
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BootPackApplicationTests {
@Value("${person.lastName}")
String lastName;
@Test
public void test01() {
log.info("@Value注解方式 读取到数据:" + lastName);
}
}

方式二: Environment对象方式
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BootPackApplicationTests {
@Autowired
private Environment env;
@Test
public void test01() {
log.info("Environment对象方式 读取到数据:" + env.getProperty("person.lastName"));
}
}

方式三: @Component+@ConfigurationProperties(prefix = “XXX”) 组合注解
@Getter
@Setter
@ToString
@Component
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
private String lastName;
private String email;
private Integer age;
private String birth;
private Map<String, Object> maps;
private List<Object> lists;
private Pets pets;
@Getter
@Setter
@ToString
class Pets {
private String name;
private Integer age;
}
}

方式四: @Component+@Value(“${xxx}”)+@PropertySource(value = {“classpath:XXX.properties”}) 组合注解
- 特别注意:@PropertySource注解不支持yml配置文件
- 新建person.properties
person.last-name=张三
person.email=xxx@163.com
person.age=${random.int}
person.birth=2020/1/10
person.maps={k1:"v1",k2:"v2"}
person.lists=a,b,c
@Getter
@Setter
@ToString
@Component
@PropertySource(value = {"classpath:person.properties"})
public class Person implements Serializable {
@Value("${person.last-name}")
private String lastName;
@Value("${person.email}")
private String email;
@Value("${person.age}")
private Integer age;
@Value("${person.birth}")
private String birth;
@Value("#{${person.maps}}")
private Map<String, Object> maps;
@Value("#{'${person.lists}'.split(',')}")
private List<Object> lists;
}

方式五: @Component+@ConfigurationProperties(prefix = “XXX”)+@PropertySource(value = {“classpath:XXX.properties”}) 组合注解
- 特别注意:@PropertySource注解不支持yml配置文件
- 新建p1.properties
person.last-name=张三
person.email=xxx@163.com
person.age=${random.int}
person.birth=2020/1/10
person.maps.k1=v1
person.maps.k2=v1
person.lists=a,b,c
@Getter
@Setter
@ToString
@Component
@PropertySource(value = {"classpath:p1.properties"})
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
private String lastName;
private String email;
private Integer age;
private String birth;
private Map<String, Object> maps;
private List<Object> lists;
}
