【Spring】@ConfigurationProperties 注解的简单使用和介绍
本篇文章主要介绍SringBoot
中的@ConfigurationProperties
注解,该注解是用来获取yml
或者properties
配置文件的配置信息,下面根据一些配置信息给出案例代码进行讲解。
@ConfigurationProperties 中属性介绍
属性名称 | 介绍 |
---|---|
prefix、value | 指定属性前缀 |
ignoreInvalidFields | 是否忽略无效字段,如果设置为true,则在绑定过程中遇到无效字段不会抛出异常 下面有对该属性值的专门介绍 默认是false |
ignoreUnknownFields | 是否忽略未知字段,如果设置为true,则在绑定过程中遇到未知字段不会抛出异常 下面有对该属性值的专门介绍 默认是true |
案例代码介绍
下面在yml
配置文件中配置:
user:name: "张三"age: 18hobbies: - "看书"- "写代码"
代码实现:
@Component
@ConfigurationProperties(prefix = "user")
public class UserInfo {private String name;private int age;private List<String> hobbies;
}
这样,就能从配置文件中读取到配置的信息。
ignoreInvalidFields 属性用法
如果,我把ignoreInvalidFields
属性值设置为false
(ignoreInvalidFields
属性值默认值就是fasle
),然后把yml
配置文件中的age修改成字符串类型,这样配置文件中的类型和Class中的类型不一致就会出现错误,以下是代码案例
user:name: "张三"age: 18hobbies: - "看书"- "写代码"
代码实现:
@Component
@ConfigurationProperties(prefix = "user", ignoreInvalidFields = false)
public class UserInfo {private String name;private int age;private List<String> hobbies;
}
错误如下:
***************************
APPLICATION FAILED TO START
***************************Description:Failed to bind properties under 'user.age' to int:Property: user.ageValue: 18岁Origin: class path resource [application.yml] - 10:8Reason: failed to convert java.lang.String to int (caused by java.lang.NumberFormatException: For input string: "18岁")Action:Update your application's configuration
ignoreUnknownFields 属性用法
这里,我把ignoreUnknownFields
属性值设置为false
(ignoreUnknownFields
属性值默认值是true
),然后把UserInfo
文件中的hobbies
变量删除,这样配置文件中的类型和Class中的属性就会不一致,接下来就会出现错误,以下是代码案例
user:name: "张三"age: 18hobbies: - "看书"- "写代码"
代码实现:
@Component
@ConfigurationProperties(prefix = "user", ignoreUnknownFields = false)
public class UserInfo {private String name;private int age;
}
错误如下:
***************************
APPLICATION FAILED TO START
***************************Description:Binding to target [Bindable@31e2232f type = com.demo.UserInfo, value = 'provided', annotations = array<Annotation>[@org.springframework.boot.context.properties.ConfigurationProperties(ignoreInvalidFields=false, ignoreUnknownFields=false, prefix=user, value=user)]] failed:Property: user.hobbies[0]Value: 看书Origin: class path resource [application.yml] - 12:7Reason: The elements [user.hobbies[0],user.hobbies[1]] were left unbound.Property: user.hobbies[1]Value: 写代码Origin: class path resource [application.yml] - 13:7Reason: The elements [user.hobbies[0],user.hobbies[1]] were left unbound.Action:Update your application's configuration
End