繁体   English   中英

Spring自定义注释:如何继承属性?

[英]Spring custom annotation: how to inherit attributes?

我正在创建自己的自定义快捷方式注释,如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 {

}

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

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

在(至少)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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM