【问题标题】:Does anyone have know how to use Spring's ImportResource annotation in a "meta-annotation"?有谁知道如何在“元注释”中使用 Spring 的 ImportResource 注释?
【发布时间】:2015-12-17 09:21:56
【问题描述】:

我正在设置一个类似于 SpringBootApplication Spring Boot 提供的 Spring“元注释”。我已经能够使用此约定成功设置 ComponentScan 和 EnableAutoConfiguration 注释,但是我无法将 value 属性成功传递给 ImportResource。

这是我想做的一个简单示例:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ComponentScan(basePackages = {"com.my.package.example"})
@EnableAutoConfiguration
@ImportResource
public @interface MyMetaAnnotationExample {
    String[] value() default {};
}

但是,编译器抱怨没有将属性传递给 ImportResource。当我尝试传递该属性时,我没有想要通过 MyMetaAnnotationExample 传递的值,因此我无法设置这些值。

ComponentScan 当然可以工作,因为这是需要硬编码的东西,但 ImportResource 是需要传递值的东西。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    Spring Framework 4.2(由 Spring Boot 1.3.x 使用)放宽了对 @ImportResource 的限制,因此您应该可以为所欲为。

    您可以在元注释上使用@AliasFor 来指定其value 属性应配置ImportResource 上的value 属性。例如:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @ComponentScan(basePackages = {"com.my.package.example"})
    @EnableAutoConfiguration
    @ImportResource
    public @interface MyMetaAnnotationExample {
    
        @AliasFor(annotation=ImportResource.class, attribute="value")
        String[] value() default {};
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 2014-03-12
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 2020-09-10
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多