Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

spring - Using Custom AnnotationTransactionAttributeSource with tx:annotation-driven

I need to use a Custom AnnotationTransactionAttributeSource in order to intercept transaction attributes. Right now, I do this using the TransactionInterceptor and injecting this in TransactionAttributeSourceAdvisor .The proxies are created using DefaultAdvisorAutoProxyCreator as given below.

<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>

Here, CustomAnnotationTransactionAttributeSource extends AnnotationTransactionAttributeSource. Is there any way I can force Tx:annotation-driven to use my CustomAnnotationTransactionAttributeSource so that I could avoid all these configurations? . I read in one of the posts that this could be done by using BeanPostProcessors but not sure how to use it for this case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

<tx:annotation-driven> doesn't do anything magic, it just registers almost the same bean definitions as you do manually (see AnnotationDrivenBeanDefinitionParser).

So, you can either replace references to AnnotationTransactionAttributeSource from other beans, or replace class name property in its definition. The latter looks simplier (though more fragile with respect to changes in Spring code) and can be done by the following 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");
        }            
    }       
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...