首页 > 解决方案 > How to supply value to an annotation dynamically?

问题描述

I have created a cutom annotation with a boolean value attribute.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
    boolean value() default false;
}

The annotation should be set dynamically based on property read from a configuration file.

I've tried to inject the value directly from the configuration:

@CustomAnnotation("${xxxxx.xxxxx.enableFeature:false}")
public void apply(){}

And:

@CustomAnnotation(""#{new Boolean('${xxxxx.xxxxx.enableFeature:false}")
public void apply(){}

I'm getting the same compilation problem for both solutions:

Type mismatch: cannot convert from String to boolean


I've tried a third solution by injecting the value as variable and then using it:

@Component
public class ApplyClass {

@Value("${xxxxx.xxxxx.enableFeature:false}")
private boolean enableFeature;

@CustomAnnotation(enableFeature)
public void apply(){}

}

I've got another compilation issue:

The value for annotation attribute must be a constant expression


Even by switching the variable to constant, this is not working.

@Component
public class ApplyClass {

@Value("${xxxxx.xxxxx.enableFeature:false}")
private static final boolean enableFeature; // ---> Leads to compilation problem 

@CustomAnnotation(enableFeature")
public void apply(){}

}

So, a part from doing code smells like:

@Component
public class ApplyClass {

@Value("${xxxxx.xxxxx.enableFeature:false}")
private  boolean enableFeature; 

private static final ENABLE_FEATURE_CONSTANT = enableFeature

@CustomAnnotation(ENABLE_FEATURE_CONSTANT)
public void apply(){}

}
  1. Is that a known limitation of annotations ?
  2. Is there any recommendation or solution a part from using Strings instead of other types ?

标签: javaspring-bootannotations

解决方案


推荐阅读