我正在创建自己的自定义快捷方式注释,如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 {
}
答案 0 :(得分: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 {
}
答案 1 :(得分:2)
在(至少)Spring 4中,您可以通过指定注释中的元素来完成此操作,例如:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value = "Custom", readOnly = true)
public @interface CustomTransactional {
Propagation propagation() default Propagation.SUPPORTED;
}