- application.yml文件
student:
name: forezp
age: 12
- 实体类 student
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
- controller
@RestController
@EnableConfigurationProperties(Student.class)
public class HelloController {
@Autowired
private Student student;
@RequestMapping("hello")
public String hello() {
System.out.println(student.getName());
return testConfig.getAge()+"";
}
}
结果
访问http://localhost:8080/hello
页面会显示10
注解的作用:
- @ConfigurationProperties(prefix = “student”)
ConfigurationProperties注解除了prefix属性来配置用配置文件中的哪个前缀,还有locations配置具体哪个文件,ignoreUnknownFields = false告诉Spring Boot在有属性不能匹配到声明的域的时候抛出异常
- @EnableConfigurationProperties(Student.class)
@EnableConfigurationProperties注解告诉Spring Boot 使能支持@ConfigurationProperties,springboot还有其他方法支持@ConfigurationProperties注解,用@Configuration或者 @Component注解, 这样就可以在 component scan时候被发现了