简体   繁体   中英

How to use the value of custom annotation parameter inside the annotation

Want to create annotation which will contain multiple annotations but want to make it more configurable so that it can be more feasible to use in all scenarios

@SpringBootApplication
@ServletComponentScan(basepackages="com.example.commons.traceability")
@ComponentScan(basePackages={
    "com.example.commons.security",
    "com.example.commons.restTemplate",
    "com.example.commons.logging",
})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Microservice{
    String[] scanBasePackages() default {};
}

I want to use this application in Spring Application file but also want to make the componentScan more configurable so that apart from the default packages other package can also me included in the component scan

@Microservice(scanBasePackages={"com.example.myproject"})
public class MySpringApplciation{
    public static void main (final String[] args){
    // some code
    }
}

so as in the above code if I pass value of scanBasePackages so those packages should also be included in the component scan.

Is there any way to include values of scanBasePackages inside componentScan in custom annotation ?

Annotations on (custom) annotations are called meta-annotations.

In short: you're lucky. While Java does not allow this out of the box, Spring has a special annotation for this sort of thing: @AliasFor.

I had a similar question, and I found the answer here: Passing annotation properties to meta-annotations

(I myself am less lucky, since I need this sort of thing for reducing my JUnit5 boilerplate annotations.)

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