Spring Boot commonly used annotations @ConfigurationProperties, loose binding, data validation

insert image description here

@ConfigurationProperties

Source code analysis

The main function of @ConfigurationProperties is to bind the value of the prefix configuration item specified by the prefix attribute to this JavaBean, and use the specified prefix to bind the configuration in the configuration file. As can be seen from the following source code, if you want to bind and verify Some external properties, which can be added to a class definition or a @Bean method in a @Configuration class.

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-VImM2Y7B-1662905478732) (C:\Users\19737\AppData\Local\Temp\1662899240307.png)]

label on the class

@Data   //使用该注解需要导入Lombok依赖
@Component
@ConfigurationProperties(prefix = "userinfo")
public class UserInfo {
    
    

    private String userId;
    private String name;
}

application.ymlfile configuration content

userInfo:
  userId: 1001
  name: lucy

Next, return this object through the controller method to see if the data is bound

@RestController
public class HelloController {
    
    

    @Autowired
    private UserInfo userInfo;

    @GetMapping("/user")
    public UserInfo getUserInfo(){
    
    
        return userInfo;
    }
}

[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-MnRhfHjq-1662905478733) (C:\Users\19737\AppData\Local\Temp\1662901651671.png)]

marked on the method

The above source code says that it can be added to the @Bean method in the @Configuration class, so let's see how the annotation is used on the method!

For example, we use the operation of the druid data source. This data source belongs to a third party, so we cannot operate the source code, and we cannot find its object in the source code to annotate it, but we can configure it in the yml file. to get its properties.

  • First add the required dependencies
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.11</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  • Then configure the data source in the yml file
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
      username: root
      password: root
  • Create a configuration class, then add annotations to the class method and bind data through prefix
@SpringBootConfiguration
public class DatasourceConfig {
    
    

    @Bean
    @ConfigurationProperties(prefix = "spring.database.druid")
    public DataSource database(){
    
    
        return new DruidDataSource();
    }
}
  • Check the binding effect through the controller method
@RestController
public class HelloController {

    @Autowired
    private DataSource dataSource;

    @GetMapping("/datasource")
    public void getDataSource(){
        System.out.println(dataSource);
    }

}

Visit http://localhost/datasourceand see the console output! ! !

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-TUQj5pPc-1662905478733) (C:\Users\19737\AppData\Local\Temp\1662903883866.png)]

loosely bound

When we use the @ConfigurationProperties annotation, @ConfigurationProperties(prefix = "userinfo"), the property value given here is inconsistent with the property name in the yml file, but the binding is still successful! what is the reason? This requires mentioning Spring's loosely bound property rules. Therefore, writing in the following ways can match the property name of the class.

userInfo:
  userId: 1001 # 驼峰命名方式
  #user_id: 1002 #下划线方式
  #user-id: 1003 #烤肉串方式
  #USER_ID: 1004 # 常量方式
  name: lucycd

It should be noted that the attribute value of the prefix must be all lowercase, as shown in the figure below, an error will be reported: the prefix must be in canonical form.

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-qmhQY4nn-1662905478734) (C:\Users\19737\AppData\Local\Temp\1662904642859.png)]

Run the program, you will also be prompted in the console: The configuration property name "userInfo" is invalid; invalid character: "I"

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-mDU3htS4-1662905478734) (C:\Users\19737\AppData\Local\Temp\1662904786812.png)]

Data validation

There are many configuration files in Spring Boot, in which we can customize some corresponding property values. So are these attribute values ​​legal? How do we check? There is a JSR303 specification in Java, and we can verify some corresponding values. Write according to the specification. If it does not meet the requirements, the verification fails, otherwise, it is successful!

SpringBoot also provides a powerful data verification function, which can effectively avoid the occurrence of such problems. The specific data verification standard is given in the JSR303 specification of JAVA EE. Developers can choose the corresponding verification framework according to their own needs. Here, the verification framework provided by Hibernate is used as the implementation for data verification.

  • Import the verification package and the verification implementation package
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>
  • add annotation@Validated
  • Add validation rules to attributes
@Data
@Component
@ConfigurationProperties(prefix = "userinfo")
@Validated
public class UserInfo {
    
    

   @Max(value = 1000,message = "userid超出范围了!")
   @Min(value = 0,message = "userid不能小于0!")
   private String userId;

   @Size(min = 2,max = 5,message = "name长度应该在2-5之间")
   private String name;
}

  • Here we first enter data that does not meet the specifications to verify whether the data can be verified successfully
userInfo:
  userId: 1001
  name: lucycd
  • Write a controller method to check
@RestController
public class HelloController {

    @Autowired
    private UserInfo userInfo;

    @GetMapping("/user")
    public UserInfo getUserInfo(){
        return userInfo;
    }

}
  • Run the program, check the console, the verification is successful! ! !

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-uxuleNQx-1662905478734) (C:\Users\19737\AppData\Local\Temp\1662883054907.png)]

  • Similarly, modify the data to conform to the rules, and the program can run successfully! ! !

Of course, there are many validation rules here, such as @NotNull, @NotEmpty, @Email, etc. You can choose the appropriate annotation according to the actual situation.

[Save and upload directly (img-QxVR7AfR-1662905478735)(C:\Users\19737\AppData\Local\Temp\1662905154773.png)]

Guess you like

Origin blog.csdn.net/weixin_52986315/article/details/126810407