Several ways of Spring configuration file with annotation assignment

Several ways of annotation assignment

1. @ConfigurationProperties

The following is the application.yaml configuration file

dog:
  name: [email protected]${
    
    random.uuid}
  age: ${
    
    random.int}

people:
  age: 17
  dog:
    name: 小王
    age: 3
  list:
    - a
    - b
  map: {
    
    k: s, v: b}

Below is People.java

@Component
@Data
@ConfigurationProperties(prefix = "people") // 读取配置文件内容
public class People {
    
    
    @Value("小帅") // 配置文件里没有这一项,直接赋值
    private String name;

    private Integer age;

    private Dog dog;

    private List<String> list;

    private Map<String, String> map;
}

In order to support @ConfigurationProperties, you need to add dependencies

<dependency>
	 <groupId>org.springframework.boot</groupId>
	 <artifactId>spring-boot-configuration-processor</artifactId>
	 <optional>true</optional>
</dependency>

2. @Value

The following is the cat.properties configuration file

name=xiaoming

Below is cat.java

@Component
@Data
@PropertySource(value = "classpath:cat.properties") // 指定配置文件路径
public class Cat {
    
    
    @Value("${name}") // 正则表达式取值
    private String name;
}

3. @Validated

Below is Dog.java

@Component
@Data
@ConfigurationProperties(prefix = "dog")
@Validated
public class Dog {
    
    
    @Email // 可以配置message报错信息
    private String name;

    private Integer age;
}

The configuration file yaml is as shown above
@Email can specify the format of the name
If support is required, a dependency needs to be added in the latest version of SpringBoot

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-validation</artifactId>
 </dependency>

Guess you like

Origin blog.csdn.net/qq_41821963/article/details/122569921