SpringBoot @ConfigurationProperties注解的简单使用
作者:WinterJay 时间:2021-09-03 12:21:57
目录
源码
使用
源码
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {
@AliasFor("prefix")
String value() default "";
@AliasFor("value")
String prefix() default "";
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
使用
向注解中传入配置文件中的前缀名,如果配置文件如下:
myConfigs:
config1:
field1: f1
field2: f2
field3: f3
那么代码中的配置类应该这样写:
@Component
@ConfigurationProperties("myConfigs.config1")
public class MyConfig1 {
String field1;
String field2;
String field3;
}
如上所示,field1, field2, field3三个属性就被绑定到了对象上。
注意到我们使用了@Component,实际上我们使用配置类都是将其注入到其他类中,所以我们往往将其注册为Bean。
ignoreInvalidFields默认为false,不合法的属性的属性会默认抛出异常;
ignoreUnknownFields默认为true, 未能识别的属性会被忽略(所以打错了名字就会被忽略了)
@ConfigurationProperties(prefix="config.prefix", ignoreInvalidFields=true, ignoreUnknownFields=false)
public class MyConfig {
// fields
}
Spring Boot的绑定规则相当宽松,myField, my-field, my_field等都能识别绑定到myField上。
可以给字段设定默认值,这样配置中没有传入时会使用默认值。
@ConfigurationProperties("your.prefix")
public class YourConfig {
private String field = "Default"
// setter
}
类的字段必须要有public访问权限的setter方法。
在很多情况下public的setter方法时必须的,使用IDEA的话,这里推荐Alt+Insert(Windows, Mac使用Alt+n)生成;当然,想使用Lombok也可以
来源:https://juejin.cn/post/6961684414824710174
标签:SpringBoot,@ConfigurationProperties,注解
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java 通过反射给实体类赋值操作
2023-11-26 10:11:41
Java中synchronized的优化措施
2022-10-09 18:19:05
![](https://img.aspxhome.com/file/2023/2/69732_0s.png)
Java获取接口所有实现类的方式详解
2022-06-11 14:44:27
SpringAOP如何获取方法参数上的注解
2021-09-19 23:22:18
![](https://img.aspxhome.com/file/2023/3/73123_0s.png)
详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑
2021-06-01 07:28:41
![](https://img.aspxhome.com/file/2023/7/61237_0s.png)
Spring MVC入门_动力节点Java学院整理
2023-11-03 20:35:31
![](https://img.aspxhome.com/file/2023/3/58753_0s.jpg)
web.xml SpringBoot打包可执行Jar运行SpringMVC加载流程
2023-11-24 07:40:52
![](https://img.aspxhome.com/file/2023/9/59929_0s.jpg)
Springboot如何使用mybatis实现拦截SQL分页
2021-08-15 13:16:56
详解Java异常处理中finally子句的运用
2023-11-29 10:10:30
MyBatis中的模糊查询语句
2022-09-30 03:36:59
Java+MySQL实现学生信息管理系统源码
2023-11-28 04:29:31
![](https://img.aspxhome.com/file/2023/6/59866_0s.jpg)
Redis分布式锁实现方式及超时问题解决
2023-08-24 23:28:34
java8新特性之日期时间API
2023-06-20 09:15:50
![](https://img.aspxhome.com/file/2023/2/57602_0s.png)
本地jvm执行flink程序带web ui的操作
2022-09-03 20:49:00
spring cache注解@Cacheable缓存穿透详解
2023-12-23 13:41:25
Java从JDK源码角度对Object进行实例分析
2022-04-09 20:12:22
springboot+mybatis-plus 两种方式打印sql语句的方法
2022-12-29 13:41:11
![](https://img.aspxhome.com/file/2023/9/64379_0s.jpg)
SpringBoot如何在运行时动态添加数据源
2023-11-13 21:36:40
java寻找迷宫路径的简单实现示例
2021-07-06 13:17:50
Maven打包没有指定主类问题(xxx.jar中没有主清单属性)
2023-11-26 21:34:44