对比点 | @ConfigurationProperties | @Value |
---|---|---|
底层框架 | Spring Boot | Spring |
功能 | 批量注入配置文件中的属性 | 单个注入 |
属性setXX()方法 | 需要 | 不需要 |
复杂类型属性注入 | 支持 | 不支持 |
松散绑定 | 支持 | 不支持 |
JSR303数据校验 | 支持 | 不支持 |
SpEL表达式 | 不支持 | 支持 |
Spring Boot可以读取默认名称的配置文件,如application.properties,application.yaml。但如果文件名是其他,则需要指定。添加如下注解
如:@PropertySource("classpath:mysql.properties")
通常:@Component 等价于 @Configuration + @EnableConfigurationProperties
1.使用@ConfigurationProperties读取
配置信息:
#配置student属性
student.id = 10
student.name=xiaoming
student.sex=F#以,分割传递 数组集合
student.hobby=football,pingpong,sing#传递 map 参数
#前缀 属性名 key = value
student.course.math=89
student.course.english=99student.email=wp@163.com
javabean:必须有setter方法
@Component //将对象加入容器
@ConfigurationProperties(prefix = "student") //读取默认配置文件中的student开头的属性
@Validated //开启属性校验
public class Student {private int id;private String name;private String sex;/*** 兴趣爱好*/private List<String> hobby;/*** 成绩*/private Map course;@Emailprivate String email;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public List<String> getHobby() {return hobby;}public void setHobby(List<String> hobby) {this.hobby = hobby;}public Map getCourse() {return course;}public void setCourse(Map course) {this.course = course;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", sex='" + sex + '\'' +", hobby=" + hobby +", course=" + course +", email='" + email + '\'' +'}';}
}
2.使用@value读取
setter可省略
@Component //将对象加入容器
@Validated //开启属性校验
public class Student2 {@Value("#{2*8}") //@Value("#{2*8}")可以在#{}进行运算,并直接赋值 SpEL表达式private int id;@Value("#{student.name}")//这样也可以啊!private String name;@Value("${student.sex}")private String sex;/*** 兴趣爱好*///@Value("${student.hobby}") // 复杂类型不支持private List<String> hobby;/*** 成绩*///@Value("${student.course}") // 复杂类型不支持private Map course;@Email@Value("${student.email}")private String email;@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", sex='" + sex + '\'' +", hobby=" + hobby +", course=" + course +", email='" + email + '\'' +'}';}
}