@Value更适合单个集合使用
com.person.name=?abc!
com.person.age=18
com.person.sex=female
@Component
@Data
public class Person{@Value("${cis.person.name}")private String username;@Value("${cis.person.age}")private int age;@Value("${cis.person.sex}")private String sex;
}
在字段上直接使用@value注解
${cis.person.name}
代表属性文件里面的keycom.person.name=?abc!
com.person.age=18
com.person.sex=female
@Component
@Data
@ConfigurationProperties(prefix = "cis.person")
public class Person{@Value("${cis.person.name}")private String username;@Value("${cis.person.age}")private int age;private String sex;
}
在类名上面使用 @PropertySource("classpath:*")
注解
*代表属性文件路径
,可以指向多个配置文件路径@PropertySource({"classpath:*","classpath:*"....})
ConfigurationProperties是一个注解,可以标注在一个Class上,这样Spring Boot会从Environment中获取其属性对应的属性值给其进行注入
com.person.name=?abc!
com.person.age=18
com.person.sex=female
// 指定配置文件:resource目录下的config目录下的test1.properties
// 不指定的话默认是:resource目录下的application.properties文件
@PropertySource(value={"classpath:config/test1.properties"})
// com.city.test1指的是test1.properties中前缀
@ConfigurationProperties(prefix = "com.person")
@Component
@Data
public class Person{private String name;private String age;private String sex;
}
custom.ranking.one=First
custom.ranking.two=Second
// lombok专用注解
@Data
// 指定配置文件:resource目录下的config目录下的test1.properties
// 不指定的话默认是:resource目录下的application.properties文件
@PropertySource("classpath:config/test1.properties")
// custom指的是test1.properties中前缀
@ConfigurationProperties(prefix = "custom")
@Component
public class CustomExportPropertiesConfig {public Map customData = new HashMap<>();
}
com.test1.nodes[0]=?
com.test1.nodes[1]=a
com.test1.nodes[2]=b
com.test1.nodes[3]=c
com.test1.nodes[4]=!
// 指定配置文件:resource目录下的config目录下的test1.properties
// 不指定的话默认是:resource目录下的application.properties文件
@PropertySource(value={"classpath:config/test1.properties"})
// com.city.test1指的是test1.properties中前缀
@ConfigurationProperties(prefix = "com.test1")
@Component
@Data
public class CityCodeProperties {private List nodes= new ArrayList<>();
}
test.config.inner.username=u1
test.config.inner.password=p1
下面的代码中就指定了name属性不能为null或空字符串,如果绑定后的值为空将抛出异常。
@Validated
@ConfigurationProperties("test.config")
@Data
public class TestConfigurationProperties {@NotBlank(message="参数test.config.name不能为空")private String name;}
如果需要进行属性值绑定的属性是一个对象,需要对该对象中的某个属性进行合法性校验,比如下面代码中需要对Inner对象中的username属性进行非空校验,则需要在inner属性上加上@Valid,同时在username属性上加上@NotBlank。
@Validated
@ConfigurationProperties("test.config")
@Data
public class TestConfigurationProperties {@Validprivate Inner inner;@Datapublic static class Inner {@NotBlank(message="参数test.config.inner.username不能为空")private String username;private String password;}}
test.config.inner.username=u1
test.config.inner.password=p1
@ConfigurationProperties("test.config")
@Data
public class TestConfigurationProperties {private Inner inner;@Datapublic static class Inner {private String username;private String password;}}
每个方法里面的@Data
注解最好不要省略,如果要省略需要给所有字段添加setter方法