一、作用
使用@ConfigurationProperties能够批量注入配置文件的属性。
二、@ConfigurationProperties注解与@Value注解区别
1.@ConfigurationProperties能够批量注入配置文件的属性。
2.@Value只能一个个指定。
3.@ConfigurationProperties支持松散绑定。
@ConfigurationProperties(prefix = "person"),只需要指定一个前缀,就能绑定有这个前缀的所有属性值。
4.@Value不支持复杂类型封装注解。
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value,如果我们需要专门编写一个JavaBean和配置文件进行映射,就直接使用ConfigurationProperties;
三、示例代码
//使用ConfigurationProperties注解
@Data
@Configuration
@ConfigurationProperties(prefix = "person")
public class Person {
private String username;
private String sex;
private String dept;
}
PS:@ConfigurationProperties("person")表示将从配置项person读取该项的所有子项配置,并且,@Configuration表示Person也是一个Spring管理的Bean,可直接注入到其他Bean中
//使用Value注解
@Configuration
@Data
public class SecondPerson {
@Value("${person.username}")
private String username;
@Value("${person.sex}")
private String sex;
@Value("${person.dept}")
private String dept;
}
//测试代码
@RestController
public class TestController {
@Autowired
private Person person;
@Autowired
private SecondPerson secondPerson;
@GetMapping("/test")
public String test(){
String result = "person=" + person.toString() + "\tsecondPerson=" + secondPerson.toString();
System.out.println(result);
return result;
}
}
//配置文件添加
person:
username: 杜小月
sex: 女
dept: 秘书部