Spring Boot 2.3.1, with OpenJDK 14
Constraint Annotation:
@Documented
@Constraint(validatedBy = {MyConstraintAnnotationValidator.class})
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraintAnnotation {
String message() default "";
Class[] groups() default {};
Class[] payload() default {};
Class clazz();
// or, not sure: Class<?> clazz();
}
Constraint Annotation Validator:
public class MyConstraintAnnotationValidator implements ConstraintValidator<MyConstraintAnnotation, String> {
@Override
public void initialize(MyConstraintAnnotation constraintAnnotation) {
// cac is: configurableApplicationContext
Object obj = cac.getBean(constraintAnnotation.clazz());
// problem: obj doesn't provide the methods to access
// on the left side of the variable shall be also the clazz type
// which is passed to the constraint annotation
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
return true;
}
}
Usage of constraint annotation:
public class MyPojo {
...
@MyConstraintAnnotation(clazz = MyProperties.class)
private String field1;
...
// Getter/ Setter
}
Properties class:
@Component
@PropertySource("classpath:myproperties.properties")
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
// fields
// Getter / Setter
}
Via the constraint annotation I want to specify my properties class to be used in the validation process within the validator class.
But within the initialize(..)
method I cannot access the Getter / Setter
from my properties class (MyProperties.class), because configurableApplicationContext.getBean(...)
returns Object
, shall create a variable and cast it to the passed class (like MyProperties.class
).
How to create a variable which has on the left side the same type which is passed to the constraint annotation?