简体   繁体   English

属性文件中值的 Java 验证器注释

[英]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.

相关问题 将 Java 验证器用于带有 @Value 注释的 SpringBoot 属性 - Using Java validator for SpringBoot properties with @Value annotation @Value Annotation不从属性文件中注入值 - @Value Annotation not injecting values from properties file 使用属性文件中的值填充注释参数值 - Fill annotation parameter value with value from properties file 如何在属性文件的@Size注释中设置最大值? - How to set max value in @Size annotation from properties file? 如何从属性文件导入值并在注释中使用它? - How to import value from properties file and use it in annotation? 要从属性文件中获取的 @Bean 注释名称属性值 - @Bean annotation name attribute value to take from properties file 将变量传递给@Value 注释以从属性文件中读取特定属性 - Passing a variable to @Value annotation for reading specific property from properties file 从属性文件中读取列表并加载弹簧注释 @Value - Reading a List from properties file and load with spring annotation @Value 从属性文件中读取Map并使用spring注释加载@Value - Reading a Map from properties file and load with spring annotation @Value 注释值未从 springboot properties.file 中读取 - Annotation value not reading from springboot properties.file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM