【问题标题】:How to use the value of custom annotation parameter inside the annotation如何在注解中使用自定义注解参数的值
【发布时间】:2021-11-07 06:15:24
【问题描述】:

想要创建包含多个注解的注解,但想要使其更具可配置性,以便在所有场景中更可行

@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 {};
}

我想在 Spring Application 文件中使用这个应用程序,但也想让 componentScan 更具可配置性,以便除了默认包之外,其他包也可以包含在组件扫描中

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

如果我传递了 scanBasePackages 的值,那么在上面的代码中,这些包也应该包含在组件扫描中。

有没有办法在自定义注释中包含 componentScan 内的 scanBasePackages 的值?

【问题讨论】:

    标签: java spring annotations spring-annotations


    【解决方案1】:

    (自定义)注解上的注解称为元注解。

    简而言之:你很幸运。虽然 Java 不允许开箱即用,但 Spring 为这类事情提供了一个特殊的注解:@AliasFor。

    我有一个类似的问题,我找到了答案here。 here 是一个很好的来源。

    具体你的情况,试试这个:

    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.core.annotation.AliasFor;
    
    @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{
    
      // >>> TRY THIS <<<
      @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
      String[] scanBasePackages() default {};
    }
    

    (我自己就没那么幸运了,因为我需要这种东西来减少我的 JUnit5 样板注释,而 @AliasFor 只在 Spring 中有意义。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多