首页 文章

一个Service方法为Spring事务调用内部多重方法

提问于
浏览
7
package com.bluesky;

public interface FooServiceIface {
    public  void insertA();
    public void insertB();
}

package com.bluesky;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class FooServiceImpl extends JdbcDaoSupport implements FooServiceIface {

    public void insertA() {
        this.getJdbcTemplate().execute("insert student(name) values('stuA')");
         insertB();
         int i=10/0;
    }

    public void insertB() {
        this.getJdbcTemplate().execute("insert student(name) values('stuB')");

    }

}

public class Client {

    public static void main(String[] args) {

        ApplicationContext appContxt = new ClassPathXmlApplicationContext("applicationContext.xml");

        FooServiceIface  fService= (FooServiceIface)appContxt.getBean("fooService");

        fService.insertA();

    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8"/>
       <property name="username" value="root"/>
       <property name="password" value="root"/>
    </bean>

    <bean id="fooService" class="com.bluesky.FooServiceImpl">
         <property name="dataSource" ref="dataSource"/>  
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource"/>  
    </bean>  

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="insertA" propagation="REQUIRED" />
             <tx:method name="insertB" propagation="REQUIRES_NEW" />
        </tx:attributes>
    </tx:advice>

    <aop:config proxy-target-class="true">
        <aop:pointcut id="interceptorPointCuts" expression="execution(* com.bluesky.*Service*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />       
    </aop:config>     
</beans>

对不起复杂的代码

当我运行客户端打击调试日志显示:

21:44:19,546 DEBUG TransactionSynchronizationManager:183 - Bound value [org.springframework.jdbc.datasource.ConnectionHolder@ba86ef] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@1b9658e] to thread [main]
21:44:19,546 DEBUG TransactionSynchronizationManager:258 - Initializing transaction synchronization
21:44:19,547 DEBUG TransactionInterceptor:362 - Getting transaction for [com.bluesky.FooServiceImpl.insertA]
21:44:19,547 DEBUG JdbcTemplate:416 - Executing SQL statement [insert student(name) values('stuA')]
21:44:19,592 DEBUG JdbcTemplate:416 - Executing SQL statement [insert student(name) values('stuB')]
21:44:19,594 DEBUG TransactionInterceptor:406 - Completing transaction for [com.bluesky.FooServiceImpl.insertA] after exception: java.lang.ArithmeticException: / by zero
21:44:19,594 DEBUG RuleBasedTransactionAttribute:130 - Applying rules to determine whether transaction should rollback on java.lang.ArithmeticException: / by zero
21:44:19,594 DEBUG RuleBasedTransactionAttribute:147 - Winning rollback rule is: null
21:44:19,595 DEBUG RuleBasedTransactionAttribute:152 - No relevant rollback rule found: applying default rules
21:44:19,595 DEBUG DataSourceTransactionManager:938 - Triggering beforeCompletion synchronization
21:44:19,595 DEBUG DataSourceTransactionManager:843 - Initiating transaction rollback
21:44:19,596 DEBUG DataSourceTransactionManager:279 - Rolling back JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@167f4bf]
21:44:19,598 DEBUG DataSourceTransactionManager:967 - Triggering afterCompletion synchronization
21:44:19,598 DEBUG TransactionSynchronizationManager:316 - Clearing transaction synchronization

我发现当调用 insertA() 方法时,这个方法启动一个事务,当代码到达 insertB() 时,没有事务要启动 .

有没有我没有配置或任何问题我弄错了

我的意图是当 insertA() 调用 insertB( )时有一个 REQUIRES_NEW 事务启动 .

3 回答

  • 4

    KLE关于重构代码的建议是正确的,但至于为什么它不起作用,Spring AOP默认使用JDK dynamic proxies来提供AOP . 这意味着当您将服务注入某些内容时,实际注入的是实现服务接口的Proxy实例 . 在此代理上调用方法时,它会在委派给您的实际服务实例之前运行事务代码 . 一旦控制流在你的服务中,通过 this.foo() 调用另一个方法(即使 this 是隐式的)只是在同一个实例上调用一个方法:你的服务 . 它不会回到代理,这是唯一知道事务的东西 . 使用AspectJ进行构建或加载时字节码编织,然后你可以这样做,它可以按预期工作,因为事务调用代码将直接编织到你的服务代码中,而不是生活在一个单独的对象中 .

  • 2

    我理解你的问题 . 有一些技术上复杂的方法可以使它工作,但我们通常不认为它们是值得的 . 我建议另一种方法,简单而强大,实际上可以改进您的代码 .

    不要将它们放在同一个Spring bean上,而是将它们放在两个不同的Beans上,B注入A中 .

    我知道我没有回答你的问题,但考虑一下这些优点:

    • 死简单,它会花费你非常 little time now .

    • 要求新的交易,B可能是另一个问题 . 有一个不同的关注点是一个不同的类似乎正是我们正在寻找的, good design .

    • 你没有任何新的和复杂的东西向你的同事解释(或者为未来的开发者提供文件),它的简单性使其立即成为 understandable .

  • 5

    KLE的答案是坚实的建议 . 只是为了完成图片,有一个解决方法,但它打破了AOP所代表的一切:

    public void insertA() {
        this.getJdbcTemplate().execute("insert student(name) values('stuA')");
        // this works, but... gah!
        ((FooServiceIface) AopContext.currentProxy()).insertB();
        int i=10/0;
    }
    

    Reference:

相关问题