如何使用AspectJ weaver自定义注释创建Spring

时间:2015-12-09 15:14:48

标签: java spring annotations aspectj

在我们的项目中,我们试图从Spring标准AOP转移到AspectJ,如this等许多地方所解释的那样(我们需要使用事务处理一些私有和受保护的方法)。

我们已经能够使用@Transactional之类的标准Spring注释使这项工作正常。但是我们面临的问题是,在我们的项目中,有一些自定义注释(不是自定义方面),AspectJ无法识别。例如,我们有一个“扩展”@Transactional的注释(仅修改rollbackFor属性):

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.CLASS)
@Transactional(rollbackFor = Exception.class)
public @interface TransactionalWithCheckedException {

}

关于如何告诉AspectJ织布这个自定义注释的任何想法?可能吗?如果没有,我应该构建自定义的Aspects扩展Spring(即:@Transactional)。

有关更多信息,请参阅aop.xml:

<aspectj>
  <aspects>
    <!-- Aparently no need to explicit declare aspects like the ones used by Spring @Transactional or @Async, they work fine. -->
  </aspects>
<weaver options="-XnoInline -Xreweavable -showWeaveInfo">
  <include within="com.mycompany.myproject..*" />
</weaver>

Spring的上下文配置文件的一部分:

 <tx:annotation-driven mode="aspectj" />
 <context:load-time-weaver />

1 个答案:

答案 0 :(得分:1)

嗯,首先,Spring @Transactional注释不是元注释,因此它不能用于注释类型。此外,spring事务代码中的任何内容都不支持这种用法。为了支持这种用法,您必须使用正确的切入点创建一个专门的方面来识别事务边界处的连接点,可能支持原始的Spring @Transactional注释和您的自定义注释。好。您还需要为方面提供TransactionAttributeSource的实现,以支持您自己的元数据源,在您的情况下,该接口的实现处理@TransactionalWithCheckedException注释(您的兴趣点将是TransactionAttribute.rollbackOn(Throwable ex)方法)。然后,您可以使用CompositeTransactionAttributeSource作为TransactionAttributeSource的实现,以便您可以合并支持Spring @Transactional注释的元数据源以及您的注释。

总结一下,你需要这两件事来处理特殊的交易属性:

  • 支持你和Spring注释的具体方面(可能是AbstractTransactionAspect的子类,请参阅AnnotationTransactionAspect了解实现方法。
  • 处理您的交易注释的TransactionAttributeSource实施。使用CompositeTransactionAttributeSource将对元数据的支持与spring的元数据(AnnotationTransactionAttributeSource)结合起来。
相关问题