Springboot中的配置文件值注入
1.@ConfigurationPerporties:
告诉Springboot将此类中的属性与配置文件的相关配置进行绑定。
此注解中存在perfix属性,是为了将配置文件具体内容与该类进行映射
yml配置文件内容:
person:
name: 张三
gender: 男
age: 20
card: {k1: VIP,k2: superVIP}
department: 经理
实体类:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Map;
//一定要先将实体类加入容器中
@Component
@ConfigurationProperties(prefix = "person")
//此处实现jsr303校验
@Validated
public class person {
@Email
private String name;
private String gender;
private Integer age;
private Map<String,String> card;
private String department;
}
2.@PerportySource:
此注解可以实现对于在多个配置文件的情况下,对于指定的配置文件进行加载。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Map;
//加载指定的配置文件
@PerportySource(value = {"classpath:person.properties"})
//一定要先将实体类加入容器中
@Component
@ConfigurationProperties(prefix = "person")
//此处实现jsr303校验
@Validated
public class person {
@Email
private String name;
private String gender;
private Integer age;
private Map<String,String> card;
private String department;
}```