【问题标题】:Using Custom AnnotationTransactionAttributeSource with tx:annotation-driven使用带有 tx:annotation-driven 的自定义 AnnotationTransactionAttributeSource
【发布时间】:2012-01-09 03:30:18
【问题描述】:

我需要使用自定义 AnnotationTransactionAttributeSource 来拦截事务属性。现在,我使用 TransactionInterceptor 执行此操作并将其注入 TransactionAttributeSourceAdvisor 。代理是使用 DefaultAdvisorAutoProxyCreator 创建的,如下所示。

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
    <property name="transactionInterceptor" ref="txInterceptor"/>
</bean>

<bean id="txInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <property name="transactionManager" ref="txManager"/>
    <property name="transactionAttributeSource"> 
       <bean class="org.myProject.transaction.CustomAnnotationTransactionAttributeSource"/>
    </property>
</bean>

这里,CustomAnnotationTransactionAttributeSource 扩展了 AnnotationTransactionAttributeSource。有什么办法可以强制 Tx:annotation-driven 使用我的 CustomAnnotationTransactionAttributeSource 以便我可以避免所有这些配置? .我在其中一篇文章中读到,这可以通过使用 BeanPostProcessors 来完成,但不确定如何在这种情况下使用它。

【问题讨论】:

    标签: spring spring-transactions


    【解决方案1】:

    &lt;tx:annotation-driven&gt; 不会做任何神奇的事情,它只是注册几乎与您手动注册相同的 bean 定义(请参阅AnnotationDrivenBeanDefinitionParser)。

    因此,您可以替换其他 bean 对 AnnotationTransactionAttributeSource 的引用,或者替换其定义中的类名属性。后者看起来更简单(虽然在 Spring 代码的更改方面更脆弱),可以通过以下BeanFactoryPostProcessor 来完成:

    public class AnnotationTransactionAttributeSourceReplacer implements BeanFactoryPostProcessor {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
                throws BeansException {
    
            String[] names = factory.getBeanNamesForType(AnnotationTransactionAttributeSource.class);
    
            for (String name: names) {
                BeanDefinition bd = factory.getBeanDefinition(name);
                bd.setBeanClassName("org.myProject.transaction.CustomAnnotationTransactionAttributeSource");
            }            
        }       
    }
    

    【讨论】:

    • 仅作记录,当使用 &lt;tx:annotation-driven /&gt; 的东西时,您没有直接定义 AnnotationTransactionAttributeSource bean,但这似乎可以替换您默认获得的那个。谢谢!
    • 我体验到控制流没有从getBeanNamesForType返回。使用 getBeanNamesForType 和附加参数 false 和 false 解决了这个问题。
    猜你喜欢
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多