[英]Java validator annotation for value from properties file
I am trying to write a Validator that should validate the value of a property in application.properties
我正在尝试编写一个验证器来验证application.properties
中的属性值
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BaseUrlStartsWithHttpsValidator.class)
public @interface CheckBaseUrlStartsWithHttps {
String message() default "Base url does not start with https:// check your configuration, "
+ "Found: ${validatedValue}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value() default "";
}
It's a simple validation I am just checking if the String starts with https://
.这是一个简单的验证,我只是检查 String 是否以https://
开头。
and the way I am trying to use it by annotating the field with it so:以及我试图通过用它注释字段来使用它的方式:
@CheckBaseUrlStartsWithHttps
@Value("${my.base.url}")
private String baseUrl;
But it seems not to do the trick I have tried changing the @Target
type is it even possible to validate properties this way, I am using Spring Framework.但它似乎没有做我尝试更改@Target
类型的技巧,是否甚至可以通过这种方式验证属性,我正在使用 Spring Framework。
So figured it out my self upon reading, reading, reading and trying different things.所以通过阅读,阅读,阅读和尝试不同的事情,我自己弄清楚了。 Turns out that in the class where I am reading in the property I had to annotate the class itself with @Validated
and @ConfigurationProperties(prefix = "my")
then my check was working as supposed to.事实证明,在我正在读取属性的类中,我必须使用@Validated
和@ConfigurationProperties(prefix = "my")
注释类本身,然后我的检查按预期工作。 So the end product is:所以最终产品是:
public class BaseUrlValidator implements ConstraintValidator<CheckBaseUrl, String> {
@Override
public boolean isValid(@Nullable String value, @Nullable ConstraintValidatorContext context) {
if (value == null) {
return false;
}
return value.startsWith("https://");
}
}
and和
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BaseUrlValidator.class)
public @interface CheckBaseUrl {
String message() default "Base URL should start with https://. Found: ${validatedValue}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value() default "";
}
and和
@Service
@Validated
@ConfigurationProperties(prefix = "my")
public class MyService {
@CheckBaseUrl
@Value("${my.base.url}")
private String baseUrl;
...
}
Only thing that might be a bit annoying though is that this will make the application fail on startup if the urls is not configured correctly, which is in its own probably a good thing such that it can be fixed right away, but I would rather want it to fail on runtime when it is accessed and throw a RumetimeException instead.唯一可能有点烦人的是,如果 url 配置不正确,这将使应用程序在启动时失败,这本身可能是一件好事,可以立即修复,但我宁愿当它被访问时它在运行时失败并抛出一个 RumetimeException 。 Anyway this seems to do the trick.无论如何,这似乎可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.