Use application.properties value in interface annotation

Federico Gatti :

Can application.properties values be used inside an annotation declaration, or more generally inside an Interfance? For example I have:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EndLogging {
    String BusinessOperationName() default  "NOME_BUSINESSOPERATIONNAME_UNDEFINED";
    String ProcessName() default "NOME_MICROSERVZIO_UNDEFINED";
}

But I want that the default value returned by the method is an application.properties value, something likes:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EndLogging {
    String BusinessOperationName() default  @Value("${business.value}");
    String ProcessName() default @Value("${process.value}");
}
Jesper :

No, this is not (directly) possible.

The default value of an annotation property must be a compile-time constant. The values that you are trying to inject from application.properties are not compile-time constants.

What you can do is use a special marker value as the default value, and then in the logic that processes your annotation recognize this special marker value and then use a value that you for example get from your properties file.

For example, if you would use your first version of the @EndLogging annotation and you would have a Spring bean that processes this annotation, it would look something like this:

// Class that processes the @EndLogging annotation
@Component
public class SomeClass {

    @Value("${business.value}")
    private String defaultBusinessOperationName;

    @Value("${process.value}")
    private String defaultProcessName;

    public void processAnnotation(EndLogging annotation) {
        // ...

        String businessOperationName = annotation.BusinessOperationName();
        if (businessOperationName.equals("NOME_BUSINESSOPERATIONNAME_UNDEFINED")) {
            businessOperationName = defaultBusinessOperationName;
        }

        String processName = annotation.ProcessName();
        if (processName.equals("NOME_MICROSERVZIO_UNDEFINED")) {
            processName = defaultProcessName;
        }

        // ...
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115601&siteId=1