简体   繁体   中英

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

@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:// .

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.

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. 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. Anyway this seems to do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM