Overview
In the project development process, a certain function needs to rely on the parameters configured in the configuration file. At this time, the following phenomena may occur:
Sometimes the project is started often, and an exception occurs when a certain functional component is used, indicating that the parameter is not configured or the bean injection fails.
Is there a way to verify the parameters when the project is started instead of throwing out the prompt when it is actually used?
The answer is to use the Java Validation function provided by Spring, which is simple and practical.
Increase startup verification
Just add Validation related configuration to the configuration Properties class we created
@Validated
@Data
@ConfigurationProperties(prefix = "app")
@Component
public class AppConfigProperties {
@NotEmpty(message = "配置文件配置必须要配置[app.id]属性")
private String id;
}
The above configuration will check us application.yml
have no configuration app.id
parameters. If there is no such configuration in the configuration file, the project will fail to start and a verification exception will be thrown.
When using configuration file verification, you must use the @configurationproperties annotation. @value does not support this annotation.
Just inject the configuration class when you need to use app.id:
@Autowired
private AppConfigProperties appConfigProperties;
In this way, we can achieve the effect we want, as shown below:
Check type
Validation rules | Rule description |
---|---|
@Null | Limit can only be null |
@NotNull | Limit must not be null |
@AssertFalse | Limit must be false |
@AssertTrue | Limit must be true |
@DecimalMax(value) | The limit must be a number not greater than the specified value |
@DecimalMin(value) | The limit must be a number not less than the specified value |
@Digits(integer,fraction) | The limit must be a decimal, and the digits of the integer part cannot exceed integer, and the digits of the decimal part cannot exceed fraction |
@Future | The limit must be a date in the future |
@Max(value) | The limit must be a number not greater than the specified value |
@Min(value) | The limit must be a number not less than the specified value |
@Past | Verify that the element value (date type) of the annotation is earlier than the current time |
@Pattern(value) | The restriction must conform to the specified regular expression |
@Size(max,min) | Limit the character length must be between min and max |
@NotEmpty | Verify that the element value of the annotation is not null and not empty (string length is not 0, collection size is not 0) |
@NotBlank | Verify that the element value of the annotation is not empty (not null, and the length is 0 after removing the first space), which is different from @NotEmpty, @NotBlank is only applied to the string and will remove the space of the string during comparison |
Verify that the element value of the annotation is Email, and you can also specify a custom email format through regular expressions and flags |
Validation supports the following types of verification, which can meet the basic business logic. Of course, if you still cannot meet your business logic, you can choose to customize the verification rules.
Custom verification logic
Define verification logic rules to achieve
org.springframework.validation.Validator
public class ConfigPropertiesValidator implements Validator {
@Override
public boolean supports(Class<?> aClass) {
return AppConfigProperties.class.isAssignableFrom(aClass);
}
@Override
public void validate(Object o, Errors errors) {
AppConfigProperties config = (AppConfigProperties) o;
if(StringUtils.isEmpty(config.getId())){
errors.rejectValue("id", "app.id.empty", "[app.id] 属性必须要在配置文件配置");
}else if (config.getId().length() < 5) {
errors.rejectValue("id", "app.id.short", "[app.id] 属性的长度必须不能小于5");
}
}
}
If you use custom validation rules, you don’t need to use the native @NotEmpty, delete it
@Validated
@Data
@ConfigurationProperties(prefix = "app")
@Component
public class AppConfigProperties {
// @NotEmpty(message = "配置文件配置必须要配置[app.id]属性")
private String id;
}
Inject custom validation rules
@Bean
public ConfigPropertiesValidator configurationPropertiesValidator(){
return new ConfigPropertiesValidator();
}
"Note: The method name of the bean here must be configured withPropertiesValidator, otherwise the verification will not be performed at startup."
Modify the app.id configuration and observe the startup
The error message is the result of our custom check.
summary
By configuring the Spring Boot startup verification function, you can quickly identify parameter configuration errors, avoid discovering problems when using components, reduce the workload of troubleshooting, and have a better way when we encapsulate our custom starter Experience.
If this article is helpful to you,
Don’t forget to give me a triple:
Like, repost, comment
。
See you next time!
Favorite equal to the white prostitute , thumbs up is the truth!
End
Dry goods sharing
Here is a small gift for everyone, follow the official account, enter the following code, you can get the Baidu network disk address, no routines!
001: "A must-read book for programmers"
002: "Building back-end service architecture and operation and maintenance architecture for small and medium-sized Internet companies from scratch"
003: "High Concurrency Solutions for Internet Enterprises"
004: "Internet Architecture Teaching Video"
006: " SpringBoot realizes ordering system"
007: "SpringSecurity actual combat video"
008: "Hadoop actual combat teaching video"
010: WeChat exchange group
Recent hot articles top
1. Solutions for automatic renewal of JWT Token
2. Do not understand ETL yet, take a look at this article?
3. Why do microservices need an api gateway
4. Architect's Road-Microservice Technology Selection
5. RocketMQ Advanced-Transaction Message
I knew you were "watching"