概述
简介
springboot 通过 properties,yaml 注入字符串,对象,list,特殊字符,以及 @Value 设置默认值,@Validated 校验等
一、properties 文件
student.properties
# string
student.name=admin
# map
student.map[id]=5
student.map[age]=22
student.map[birthday]='2222-02-22'
# list
student.subject='java','c','c++'
maps={'a':'aa','b':'bb','c':'cc'}
注入实体类
@Data // 必须提供 get/set 方法
@Configuration // 或者 @Component
// 指定引用哪个配置文件. 在 application.yml 中使用了 spring.profiles.include 引用配置文件,可以不写下面的注解
@PropertySource(value = "classpath:student.properties")
@ConfigurationProperties(prefix = "student")
public class StudentBean {
private String name;
// 注意:封装对象不能使用@Value,下面的是特例
// 注意:成员变量名要和配置文件中配置的参数名一致
// 注意:不能直接给静态变量赋值,静态变量可以在 set 方法上使用 @Value 注入
private Map<String, String> map;
private List<String> subject;
@Value("#{${maps}}") // 注意这里的 #
private Map<String, String> maps;
}
测试(我的 SpringbootTest 测试跑不起来,暂时在 main 方法测试)
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(SxdlSzhgdsApiDwsApplication.class, args);
StudentBean studentBean = configurableApplicationContext.getBean(StudentBean.class);
System.out.println(studentBean.getName()); // admin
System.out.println(studentBean.getMap().get("birthday")); // '2222-02-22'
System.out.println(studentBean.getSubject().get(0)); // 'java'
System.out.println(studentBean.getMaps().get("a")); // aa
}
二、yam 或 yaml 文件
为什么要区分 properties 和 yaml: 因为 @PropertySource 默认只能解析 properties,不解析 yaml
添加如下解析类,参考 https://blog.csdn.net/cockroach02/article/details/105188955
// 继承DefaultPropertySourceFactory
public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null) {
return super.createPropertySource(name, resource);
}
Resource resourceResource = resource.getResource();
if (!resourceResource.exists()) {
return new PropertiesPropertySource(null, new Properties());
} else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource);
return sources.get(0);
}
return super.createPropertySource(name, resource);
}
}
student.yaml
注意这个下面 * 就是特殊字符,如果不使用 [],则注入不进去,并且需要添加双引号
# string
address:
name: root
student:
name: admin
# map
map:
id: 5
age: 22
birthday: '2222-02-22'
'[*]': '☀'
# list
subject: ['java','c','c++']
maps: {'a':'aa','b':'bb','c':'cc'} # 注意这个缩进, student.maps,和 properties 不同
注入实体类
@Data // 必须提供 get/set 方法
@Configuration // 或者 @Component
// 指定自定义的解析类,否则对象数组复杂类型注入不进去
// 如果将 student.yaml 配置添加到 application.yaml 可以注入,不需要添加解析类
@PropertySource(value = "classpath:student.yaml",factory = YamlAndPropertySourceFactory.class)
@ConfigurationProperties(prefix = "student")
public class StudentBean {
// @Value 和 @ConfigurationProperties 同时存在,@ConfigurationProperties 覆盖 @Value
@Value("${address:shanghai}") // success: 因为在 yaml 中定义 address ,虽然没有写默认空字符串 ''
private String address;
@Value("${phone:72190053}") // success: 注入 phone = 72190053
private String phone;
@Value("${name}") // @ConfigurationProperties 覆盖 @Value 最终结果 admin
private String name;
private Map<String, String> map;
private List<String> subject;
private Map<String, String> maps;
}
测试(我的 SpringbootTest 测试跑不起来,暂时在 main 方法测试)
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(SxdlSzhgdsApiDwsApplication.class, args);
StudentBean studentBean = configurableApplicationContext.getBean(StudentBean.class);
System.out.println(studentBean.getAddress()); // ''
System.out.println(studentBean.getPhone()); // 72190053
System.out.println(studentBean.getName()); // admin
System.out.println(studentBean.getMap()); // {id=5, age=22, birthday=2222-02-22, *=☀}
System.out.println(studentBean.getMap().get("birthday")); // '2222-02-22'
System.out.println(studentBean.getSubject().get(0)); // 'java'
System.out.println(studentBean.getMaps().get("a")); // aa
}
三、@ConfigurationProperties 和 @Value 的区别
@ConfigurationProperties | @Value | |
---|---|---|
注解功能 | 可以批量注入配置文件中的属性 | 只能一个个指定注入属性 |
松散语法绑定(Relaxed binding) | 支持 | 不支持 |
EL表达式 | 不支持 | 支持 |
JSR303数据校验 @Validated | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
注意:
- 配置文件中如果你定义了一个属性,没有任何值,默认为 ‘’, 在使用 @Value 赋默认值时只有为 null 才生效
- @Value 和 @ConfigurationProperties 同时存在,@ConfigurationProperties 覆盖 @Value
四、 @Validated 校验
@Value 可以赋默认值,@ConfigurationProperties 则可以使用 @Validated 校验判断注入属性是否合法(当然 @Validated 可以用在其他参数传递的地方,也可以结合 @Value 使用)
1、@Validated 支持校验
@Null | 限制只能为null |
@NotNull | 限制必须不为null |
@AssertFalse | 限制必须为false |
@AssertTrue | 限制必须为true |
@DecimalMax(value) | 限制必须为一个不大于指定值的数字 |
@DecimalMin(value) | 限制必须为一个不小于指定值的数字 |
@Digits(integer,fraction) | 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction |
@Future | 限制必须是一个将来的日期 |
@Max(value) | 限制必须为一个不大于指定值的数字 |
@Min(value) | 限制必须为一个不小于指定值的数字 |
@Past | 限制必须是一个过去的日期 |
@Pattern(value) | 限制必须符合指定的正则表达式 |
@Size(max,min) | 限制字符长度必须在min到max之间 |
@Past | 验证注解的元素值(日期类型)比当前时间早 |
@NotEmpty | 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
@NotBlank | 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格 |
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
2、简单使用
导入 validation 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
student.yaml 文件
email: 123456
student:
name: root
StudentBean 实体类
@Data // lombok
@Configuration
@PropertySource(value = "classpath:student.yaml",factory = YamlAndPropertySourceFactory.class)
@ConfigurationProperties(prefix = "student")
@Validated
public class StudentBean {
@Value("${email}")
@Email
private String email;
private String name;
}
测试,会说明 email 属性格式不正确
最后
以上就是含蓄纸鹤为你收集整理的springboot 注入实例相关记录的全部内容,希望文章能够帮你解决springboot 注入实例相关记录所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复