Search code examples
javaspringspring-bootexceptionannotations

Using @Value for a @CustomAnnotation in SpringBoot


I've read similar questions and relative answers but didn't find one whose fit.

In the given sample:

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = DescriptionValidationImpl.class)
public @interface DescriptionValidation {

    public String message() default "default"; 

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

How can i read a value from the .properties file and assign it to the message, knowing that @Value isn't a compile-time constant?

Heard someone doing with the ExceptionHandlrController, is it possible? How?
And if i were in need of different messages for the same catched exc?

I've tried the following too even if it didn't make no sense for me:

@Component
@PropertySource(value = "classpath:message.properties")
public class DescriptionProcessing {

    @Value("${description}")
    private String descriptionErrorMsg;

    public void processAnnotation(DescriptionValidation annotation) {

        String defaultDescriptionErrorMsg = annotation.message();

        if (defaultDescriptionErrorMsg.equals("default"))
            defaultDescriptionErrorMsg = descriptionErrorMsg;
    }
}

But kept printing the default one.


Solution

  • Solved! Using a bean in a config file and calling it back from the excHandlr.

    In the @Annotation @interface were in need of the placeholder of @Value i.e.

    public String message() default "description";
    

    in the given example but'll probably be something like "error.description" or whatever