G006Spring學習筆記-IOC案例完善

一、完善account案例

1、添加轉賬方法

代碼:

接口IAccountDao:

package com.zibo.dao;

import com.zibo.domain.Account;

import java.util.List;

public interface IAccountDao {
    //查詢所有賬戶
    List<Account> findAllAccount();
    //根據id查詢賬戶
    Account findAccountById(Integer accountId);
    //保存賬戶
    void saveAccount(Account account);
    //更新賬戶
    void updateAccount(Account account);
    //刪除用戶
    void deleteAccountById(Integer accountId);

    /**
     * 通過名字查詢賬戶
     * @param accountName       賬戶名字
     * @return                  賬戶
     * 備註:如果有唯一的一個結果就返回,如果沒有結果返回null,如果結果超過一個拋異常
     */
    Account findAccountByName(String accountName);
}

接口實現類AccountDaoImpl:

package com.zibo.dao.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 賬戶的持久層實現類
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<>(Account.class));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?",new BeanHandler<>(Account.class),accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            runner.update("update account set name = ?, money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        try {
            runner.update("delete from account where id = ?",accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    //轉賬
    @Override
    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query("select * from account where name = ?",new BeanListHandler<>(Account.class),accountName);
            if(accounts==null || accounts.size()==0){
                return null;
            }else if(accounts.size()==1){
                return accounts.get(0);
            }else {
                throw new RuntimeException("結果不唯一,數據錯誤!");
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

接口IAccountService:

package com.zibo.service;

import com.zibo.domain.Account;

import java.util.List;

/**
 *  賬戶的業務層接口
 */
public interface IAccountService {
    //查詢所有賬戶
    List<Account> findAllAccount();
    //根據id查詢賬戶
    Account findAccountById(Integer accountId);
    //保存賬戶
    void saveAccount(Account account);
    //更新賬戶
    void updateAccount(Account account);
    //刪除用戶
    void deleteAccountById(Integer accountId);

    /**
     * 轉賬
     * @param sourceName    轉出者名字
     * @param targetName    轉入者名字
     * @param money         轉賬金額
     */
    void transfer(String sourceName,String targetName,float money);
}

接口實現類AccountServiceImpl:

package com.zibo.service.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.domain.Account;
import com.zibo.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 賬戶的業務層實現類
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        accountDao.deleteAccountById(accountId);
    }
    //轉賬
    @Override
    public void transfer(String sourceName, String targetName, float money) {
        //1、根據名稱查詢轉出賬戶;
        Account source = accountDao.findAccountByName(sourceName);
        //2、根據名稱查詢轉入賬戶;
        Account target = accountDao.findAccountByName(targetName);
        //3、轉出賬戶減錢;
        source.setMoney(source.getMoney()-money);
        //4、轉入賬戶加錢;
        target.setMoney(target.getMoney()+money);
        //5、更新轉出賬戶;
        accountDao.updateAccount(source);
        //6、更新轉入賬戶;
        accountDao.updateAccount(target);
    }
}

測試類AccountServiceTest:

package com.zibo.test;

import com.zibo.config.SpringConfiguration;
import com.zibo.domain.Account;
import com.zibo.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用junit單元測試進行測試
 * spring整合junit配置:
 *  1、導入spring整合junit的jar(座標);
 *  2、使用junit提供的註解,把原有的main方法替換成spring提供的@Runwith;
 *  3、告知spring的運行器,spring的ioc創建是基於xml還是註解,並說明其位置,使用@ContextConfiguration;
 *  ContextConfiguration:
 *      locations:指定xml文件的位置,加上classpath關鍵字,表示在類路徑下;
 *      classes:指定註解類所在的位置;
 *  備註:當我們使用5.x版本的時候,junit的jar必須是4.12以上;
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
//    private ApplicationContext ac;
    @Autowired
    private IAccountService as;
    @Before
    public void init(){
        //1、獲取容器
//        ac = new ClassPathXmlApplicationContext("bean.xml");
//        ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2、得到業務層對象
//        as = ac.getBean("accountService", IAccountService.class);
    }
    @Before
    public void end(){
//        ac.close();
    }
    @Test
    public void testFindAllAccount(){
        //3、執行方法
        List<Account> accounts = as.findAllAccount();
        //4、遍歷輸出
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindAccountById(){
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("大哥");
        account.setMoney(2000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        Account account = new Account();
        account.setId(3);
        account.setName("二哥");
        account.setMoney(3000);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        as.deleteAccountById(1);
    }
    //轉賬測試
    @Test
    public void testTransfer(){
        as.transfer("二哥","bbb",500);
    }
}

文件位置圖:

備註:

其他文件見G005Spring學習筆記-Spring完全註解實現及優化

發現問題:

    //轉賬
    @Override
    public void transfer(String sourceName, String targetName, float money) {
        //1、根據名稱查詢轉出賬戶;
        Account source = accountDao.findAccountByName(sourceName);
        //2、根據名稱查詢轉入賬戶;
        Account target = accountDao.findAccountByName(targetName);
        //3、轉出賬戶減錢;
        source.setMoney(source.getMoney()-money);
        //4、轉入賬戶加錢;
        target.setMoney(target.getMoney()+money);
        //5、更新轉出賬戶;
        accountDao.updateAccount(source);

        //在這寫一個錯誤,會導致轉賬過程中轉出賬戶錢減了,但是轉入賬戶錢沒加
        int i = 1/0;

        //6、更新轉入賬戶;
        accountDao.updateAccount(target);
    }

分析問題:

解決問題:

進行事務控制;

代碼示例:

AccountServiceImpl:

package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import com.itheima.utils.TransactionManager;

import java.util.List;

/**
 * 賬戶的業務層實現類
 *
 * 事務控制應該都是在業務層
 */
public class AccountServiceImpl_OLD implements IAccountService{

    private IAccountDao accountDao;
    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            //1.開啓事務
            txManager.beginTransaction();
            //2.執行操作
            List<Account> accounts = accountDao.findAllAccount();
            //3.提交事務
            txManager.commit();
            //4.返回結果
            return accounts;
        }catch (Exception e){
            //5.回滾操作
            txManager.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.釋放連接
            txManager.release();
        }

    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            //1.開啓事務
            txManager.beginTransaction();
            //2.執行操作
            Account account = accountDao.findAccountById(accountId);
            //3.提交事務
            txManager.commit();
            //4.返回結果
            return account;
        }catch (Exception e){
            //5.回滾操作
            txManager.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.釋放連接
            txManager.release();
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            //1.開啓事務
            txManager.beginTransaction();
            //2.執行操作
            accountDao.saveAccount(account);
            //3.提交事務
            txManager.commit();
        }catch (Exception e){
            //4.回滾操作
            txManager.rollback();
        }finally {
            //5.釋放連接
            txManager.release();
        }

    }

    @Override
    public void updateAccount(Account account) {
        try {
            //1.開啓事務
            txManager.beginTransaction();
            //2.執行操作
            accountDao.updateAccount(account);
            //3.提交事務
            txManager.commit();
        }catch (Exception e){
            //4.回滾操作
            txManager.rollback();
        }finally {
            //5.釋放連接
            txManager.release();
        }

    }

    @Override
    public void deleteAccount(Integer acccountId) {
        try {
            //1.開啓事務
            txManager.beginTransaction();
            //2.執行操作
            accountDao.deleteAccount(acccountId);
            //3.提交事務
            txManager.commit();
        }catch (Exception e){
            //4.回滾操作
            txManager.rollback();
        }finally {
            //5.釋放連接
            txManager.release();
        }

    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        try {
            //1.開啓事務
            txManager.beginTransaction();
            //2.執行操作

            //2.1根據名稱查詢轉出賬戶
            Account source = accountDao.findAccountByName(sourceName);
            //2.2根據名稱查詢轉入賬戶
            Account target = accountDao.findAccountByName(targetName);
            //2.3轉出賬戶減錢
            source.setMoney(source.getMoney()-money);
            //2.4轉入賬戶加錢
            target.setMoney(target.getMoney()+money);
            //2.5更新轉出賬戶
            accountDao.updateAccount(source);

            int i=1/0;

            //2.6更新轉入賬戶
            accountDao.updateAccount(target);
            //3.提交事務
            txManager.commit();

        }catch (Exception e){
            //4.回滾操作
            txManager.rollback();
            e.printStackTrace();
        }finally {
            //5.釋放連接
            txManager.release();
        }


    }
}

ConnectionUtils連接工具類:

package com.itheima.utils;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 連接的工具類,它用於從數據源中獲取一個連接,並且實現和線程的綁定
 */
public class ConnectionUtils {

    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 獲取當前線程上的連接
     * @return
     */
    public Connection getThreadConnection() {
        try{
            //1.先從ThreadLocal上獲取
            Connection conn = tl.get();
            //2.判斷當前線程上是否有連接
            if (conn == null) {
                //3.從數據源中獲取一個連接,並且存入ThreadLocal中
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            //4.返回當前線程上的連接
            return conn;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 把連接和線程解綁
     */
    public void removeConnection(){
        tl.remove();
    }
}

TransactionManager事務工具類:

package com.itheima.utils;

/**
 * 和事務管理相關的工具類,它包含了,開啓事務,提交事務,回滾事務和釋放連接
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 開啓事務
     */
    public  void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 提交事務
     */
    public  void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 回滾事務
     */
    public  void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 釋放連接
     */
    public  void release(){
        try {
            connectionUtils.getThreadConnection().close();//還回連接池中
            connectionUtils.removeConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

bean.xml配置文件:

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

    <!--配置代理的service-->
    <bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService"/>

    <!--配置beanfactory-->
    <bean id="beanFactory" class="com.itheima.factory.BeanFactory">
        <!-- 注入service -->
        <property name="accountService" ref="accountService"/>
        <!-- 注入事務管理器 -->
        <property name="txManager" ref="txManager"/>
    </bean>

     <!-- 配置Service -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--配置Dao對象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"/>
        <!-- 注入ConnectionUtils -->
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>

    <!-- 配置數據源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--連接數據庫的必備信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"/>
        <property name="user" value="root"/>
        <property name="password" value="1234"/>
    </bean>

    <!-- 配置Connection的工具類 ConnectionUtils -->
    <bean id="connectionUtils" class="com.itheima.utils.ConnectionUtils">
        <!-- 注入數據源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事務管理器-->
    <bean id="txManager" class="com.itheima.utils.TransactionManager">
        <!-- 注入ConnectionUtils -->
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>
</beans>

 

二、分析案例中的問題

案例中存在很多重複代碼和“牽一髮動全身”的麻煩;

 

三、技術回顧:動態代理

1、簡單案例(基於接口的動態代理)

代碼:

IProducer限制廠家的接口:

package com.zibo.proxy;

//對生產廠家要求的接口
public interface IProducer {

    //銷售
    public void saleProduct(float money);

    //售後
    public void afterService(float money);

}

Producer廠家類:

package com.zibo.proxy;

//生產者
public class Producer implements IProducer {

    //銷售
    public void saleProduct(float money){
        System.out.println("銷售產品,拿到錢" + money);
    }

    //售後
    public void afterService(float money){
        System.out.println("提供售後服務,並拿到錢" + money);
    }

}

Client模擬顧客類:

package com.zibo.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//模擬一個消費者
public class Client {
    public static void main(String[] args) {
        Producer producer = new Producer();
        /*
         * 動態代理:
         *  特點:字節碼隨用隨創建,隨用隨加載
         *  作用:不修改源碼的基礎上,對方法增強;
         *  分類:
         *      基於接口的動態代理;
         *      基於子類的動態代理;
         *  基於接口的動態代理:
         *      涉及的類:Proxy;
         *      提供者:JDK官方;
         *  如何創建代理對象:
         *      使用Proxy類中的newProxyInstance方法;
         *  創建代理對象的要求:
         *      被代理類最少實現一個接口,否則不能使用;
         *  newProxyInstance方法的參數:
         *      ClassLoader:類加載器,用於加載代理對象的字節碼,使用和被代理對象相同的類加載器,固定寫法;
         *      Class[]:用於讓代理對象和被代理對象有相同的方法,固定寫法;
         *      InvocationHandler:用於提供增強的方法,讓我們寫如何代理,一般寫該接口的實現類(匿名內部類,不是必須);
         *      此接口的實現類是誰用誰寫;
         */
        IProducer proxyProducer = (IProducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * //作用:執行被代理對象的任何接口方法都會經過該方法
                     * @param proxy 代理對象的引用
                     * @param method    當前執行的方法
                     * @param args  當前執行方法所需要的參數
                     * @return  和被代理對象有相同的返回值
                     */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //提供增強的代代碼,經銷商拿走銷售提成
                Object returnValue = null;
                //1、獲取方法執行的參數
                float money = (float) args[0];
                //2、判斷當前方法是不是銷售
                if("saleProduct".equals(method.getName())){
                    returnValue = method.invoke(producer,money * 0.8f);
                }
                return returnValue;
            }
        });
        proxyProducer.saleProduct(10000f);
    }
}

文件位置圖:

運行結果:

 

2、簡單案例(基於子類的動態代理)

改造的代碼:

Client:

package com.zibo.cglib;

 import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

//模擬一個消費者
public class Client {
    public static void main(String[] args) {
        Producer producer = new Producer();
        /*
         * 動態代理:
         *  特點:字節碼隨用隨創建,隨用隨加載
         *  作用:不修改源碼的基礎上,對方法增強;
         *  分類:
         *      基於接口的動態代理;
         *      基於子類的動態代理;
         *  基於子類的動態代理:
         *      涉及的類:Enhancer;
         *      提供者:第三方cglib庫;
         *  如何創建代理對象:
         *      使用Enhancer類中的create方法;
         *  創建代理對象的要求:
         *      被代理類不能是最終類;
         *  create方法的參數:
         *      Class:字節碼,用於指定被代理對象的字節碼;
         *      CallBack:用於提供增強的代碼;
         *      它是讓我們寫如何代理,一般寫該接口的實現類(匿名內部類,不是必須);
         *      此接口的實現類是誰用誰寫;
         *      我們一般寫的都是該接口的子接口實現類:MethodInterceptor
         */
        Producer cglibProducer = (Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             * //作用:執行被代理對象的任何接口方法都會經過該方法
             * @param proxy     見invoke
             * @param method    見invoke
             * @param args   見invoke
             * @param methodProxy   當前執行方法的代理對象
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //提供增強的代代碼,經銷商拿走銷售提成
                Object returnValue = null;
                //1、獲取方法執行的參數
                float money = (float) args[0];
                //2、判斷當前方法是不是銷售
                if("saleProduct".equals(method.getName())){
                    returnValue = method.invoke(producer,money * 0.8f);
                }
                return returnValue;
            }
        });
        cglibProducer.saleProduct(12000f);
    }
}

Producer:

package com.zibo.cglib;

//生產者
public class Producer {

    //銷售
    public void saleProduct(float money){
        System.out.println("銷售產品,拿到錢" + money);
    }

    //售後
    public void afterService(float money){
        System.out.println("提供售後服務,並拿到錢" + money);
    }

}

pom.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring09</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>
    </dependencies>


</project>

文件位置圖:

運行結果:

 

四、使用動態代理實現事務控制

代碼:

BeanFactory:

package com.itheima.factory;

import com.itheima.service.IAccountService;
import com.itheima.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用於創建Service的代理對象的工廠
 */
public class BeanFactory {

    private IAccountService accountService;

    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }


    public final void setAccountService(IAccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * 獲取Service代理對象
     * @return
     */
    public IAccountService getAccountService() {
        return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事務的支持
                     *
                     * @param proxy
                     * @param method
                     * @param args
                     * @return
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        if("test".equals(method.getName())){
                            return method.invoke(accountService,args);
                        }

                        Object rtValue = null;
                        try {
                            //1.開啓事務
                            txManager.beginTransaction();
                            //2.執行操作
                            rtValue = method.invoke(accountService, args);
                            //3.提交事務
                            txManager.commit();
                            //4.返回結果
                            return rtValue;
                        } catch (Exception e) {
                            //5.回滾操作
                            txManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            //6.釋放連接
                            txManager.release();
                        }
                    }
                });

    }
}

AccountServiceTest:

package com.itheima.test;

import com.itheima.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 使用Junit單元測試:測試我們的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    @Qualifier("proxyAccountService")
    private  IAccountService as;

    @Test
    public  void testTransfer(){
        as.transfer("aaa","bbb",100f);
    }

}

AccountServiceImpl:

package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;

import java.util.List;

/**
 * 賬戶的業務層實現類
 *
 * 事務控制應該都是在業務層
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
       return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);

    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
            //2.1根據名稱查詢轉出賬戶
            Account source = accountDao.findAccountByName(sourceName);
            //2.2根據名稱查詢轉入賬戶
            Account target = accountDao.findAccountByName(targetName);
            //2.3轉出賬戶減錢
            source.setMoney(source.getMoney()-money);
            //2.4轉入賬戶加錢
            target.setMoney(target.getMoney()+money);
            //2.5更新轉出賬戶
            accountDao.updateAccount(source);

//            int i=1/0;

            //2.6更新轉入賬戶
            accountDao.updateAccount(target);
    }
}

BeanFactory:

package com.itheima.factory;

import com.itheima.service.IAccountService;
import com.itheima.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用於創建Service的代理對象的工廠
 */
public class BeanFactory {

    private IAccountService accountService;

    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }


    public final void setAccountService(IAccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * 獲取Service代理對象
     * @return
     */
    public IAccountService getAccountService() {
        return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事務的支持
                     *
                     * @param proxy
                     * @param method
                     * @param args
                     * @return
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        if("test".equals(method.getName())){
                            return method.invoke(accountService,args);
                        }

                        Object rtValue = null;
                        try {
                            //1.開啓事務
                            txManager.beginTransaction();
                            //2.執行操作
                            rtValue = method.invoke(accountService, args);
                            //3.提交事務
                            txManager.commit();
                            //4.返回結果
                            return rtValue;
                        } catch (Exception e) {
                            //5.回滾操作
                            txManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            //6.釋放連接
                            txManager.release();
                        }
                    }
                });

    }
}

文件位置圖:

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章