【Spring】@ConfigurationProperties 注解的简单使用和介绍

文章目录

  • @ConfigurationProperties 中属性介绍
  • 案例代码介绍
  • ignoreInvalidFields 属性用法
  • ignoreUnknownFields 属性用法

本篇文章主要介绍SringBoot中的@ConfigurationProperties注解,该注解是用来获取yml或者properties配置文件的配置信息,下面根据一些配置信息给出案例代码进行讲解。

@ConfigurationProperties 中属性介绍

属性名称 介绍
prefix、value 指定属性前缀
ignoreInvalidFields 是否忽略无效字段,如果设置为true,则在绑定过程中遇到无效字段不会抛出异常
下面有对该属性值的专门介绍
默认是false
ignoreUnknownFields 是否忽略未知字段,如果设置为true,则在绑定过程中遇到未知字段不会抛出异常
下面有对该属性值的专门介绍
默认是true


案例代码介绍

下面在yml配置文件中配置:

user:
  name: "张三"
  age: 18
  hobbies: 
    - "看书"
    - "写代码"

代码实现:

@Component
@ConfigurationProperties(prefix = "user")
public class UserInfo {
    private String name;
    private int age;
    private List<String> hobbies;
}

这样,就能从配置文件中读取到配置的信息。



ignoreInvalidFields 属性用法

如果,我把ignoreInvalidFields属性值设置为falseignoreInvalidFields属性值默认值就是fasle),然后把yml配置文件中的age修改成字符串类型,这样配置文件中的类型和Class中的类型不一致就会出现错误,以下是代码案例

user:
  name: "张三"
  age: 18
  hobbies: 
    - "看书"
    - "写代码"

代码实现:

@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.age
    Value: 18岁
    Origin: class path resource [application.yml] - 10:8
    Reason: 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属性值设置为falseignoreUnknownFields属性值默认值是true),然后把UserInfo文件中的hobbies变量删除,这样配置文件中的类型和Class中的属性就会不一致,接下来就会出现错误,以下是代码案例

user:
  name: "张三"
  age: 18
  hobbies: 
    - "看书"
    - "写代码"

代码实现:

@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:7
    Reason: The elements [user.hobbies[0],user.hobbies[1]] were left unbound.
    Property: user.hobbies[1]
    Value: 写代码
    Origin: class path resource [application.yml] - 13:7
    Reason: The elements [user.hobbies[0],user.hobbies[1]] were left unbound.

Action:

Update your application's configuration





End


你可能感兴趣的:(Spring,spring,java,后端)