7

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

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

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

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

}
4

2 回答 2

4

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

@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 {
}
于 2013-01-04T13:31:13.873 回答
2

In (at least) Spring 4, you can do this by specifying the element inside the annotation, e.g.:

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

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

于 2015-07-16T19:10:02.053 回答