【问题标题】:Spring custom annotation: how to inherit attributes?Spring自定义注解:如何继承属性?
【发布时间】:2012-12-18 17:39:08
【问题描述】:

我正在创建自己的自定义快捷方式注释,如Spring Documentation 中所述:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value = "Custom", readOnly = true)
public @interface CustomTransactional {
}

是否有可能,通过我的自定义注释,我还可以设置任何其他属性,这些属性在@Transactional 中可用?我希望能够使用我的注释,例如:

@CustomTransactional(propagation = Propagation.REQUIRED)
public class MyClass {

}

【问题讨论】:

    标签: java annotations spring-annotations


    【解决方案1】:

    不,如果您想以这种方式在自定义注释本身上设置其他属性,那将不起作用:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Transactional(value = "Custom", readOnly = true, propagation = Propagation.REQUIRED)
    public @interface CustomTransactional {
    }
    

    一种解决方案(不好的一个:-))可能是使用您在场景中看到的基本案例集定义多个注释:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Transactional(value = "Custom", readOnly = true, propagation = Propagation.REQUIRED)
    public @interface CustomTransactionalWithRequired {
    }
    
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Transactional(value = "Custom", readOnly = true, propagation = Propagation.SUPPORTED)
    public @interface CustomTransactionalWithSupported {
    }
    

    【讨论】:

    • 是的,我想到了这样的场景,但是我最终会得到很多注释——对于每个合理的属性组合;)
    • 是的,我是这么认为的,这就是我把它作为一个糟糕的解决方案的原因:-)。如果是这种情况,除了使用 @Transactional 本身之外别无他法,如果您的注释有一组固定的属性,自定义构造型注释将有所帮助。
    【解决方案2】:

    在(至少)Spring 4 中,您可以通过在注解中指定元素来做到这一点,例如:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Transactional(value = "Custom", readOnly = true)
    public @interface CustomTransactional {
        Propagation propagation() default Propagation.SUPPORTED;
    }
    

    来源:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-meta-annotations

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 2016-01-21
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2011-01-31
      • 2020-05-07
      • 1970-01-01
      相关资源
      最近更新 更多