您现在的位置是:首页 > 编程 > 

【旧】G006Spring学习笔记

2025-07-24 11:05:06
【旧】G006Spring学习笔记 一、完善account案例1、添加转账方法代码:接口IAccountDao:代码语言:javascript代码运行次数:0运行复制package com.zibo.dao; import com.zibo.domain.Account; import java.util.List; public interface IAccountDao { //

【旧】G006Spring学习笔记

一、完善account案例

1、添加转账方法

代码:

接口IAccountDao:

代码语言:javascript代码运行次数:0运行复制
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 accountame       账户名字
     * @return                  账户
     * 备注:如果有唯一的一个结果就返回,如果没有结果返回null,如果结果超过一个抛异常
     */
    Account findAccountByame(String accountame);
}

接口实现类AccountDaoImpl:

代码语言:javascript代码运行次数:0运行复制
package com.zibo.dao.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.domain.Account;
import org.apachem.dbutils.QueryRunner;
import org.apachem.dbutils.handlers.BeanHandler;
import org.apachem.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<>());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

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

    @Override
    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money) values(?,?)",account.getame(),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.getame(),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 findAccountByame(String accountame) {
        try {
            List<Account> accounts = runner.query("select * from account where name = ?",new BeanListHandler<>(),accountame);
            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:

代码语言:javascript代码运行次数:0运行复制
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 sourceame    转出者名字
     * @param targetame    转入者名字
     * @param money         转账金额
     */
    void transfer(String sourceame,String targetame,float money);
}

接口实现类AccountServiceImpl:

代码语言:javascript代码运行次数:0运行复制
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 sourceame, String targetame, float money) {
        //1、根据名称查询转出账户;
        Account source = accountDao.findAccountByame(sourceame);
        //2、根据名称查询转入账户;
        Account target = accountDao.findAccountByame(targetame);
        //、转出账户减钱;
        source.setMoney(source.getMoney()-money);
        //4、转入账户加钱;
        target.setMoney(target.getMoney()+money);
        //5、更新转出账户;
        accountDao.updateAccount(source);
        //6、更新转入账户;
        accountDao.updateAccount(target);
    }
}

测试类AccountServiceTest:

代码语言:javascript代码运行次数:0运行复制
package com.;

import com.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.ApplicationContext;
import org.annotation.AnnotationConfigApplicationContext;
import org.support.ClassPathXmlApplicationContext;
import org.ContextConfiguration;
import org.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用junit单元测试进行测试
 * spring整合junit配置:
 *  1、导入spring整合junit的jar(坐标);
 *  2、使用junit提供的注解,把原有的main方法替换成spring提供的@Runwith;
 *  、告知spring的运行器,spring的ioc创建是基于xml还是注解,并说明其位置,使用@ContextConfiguration;
 *  ContextConfiguration:
 *      locati:指定xml文件的位置,加上classpath关键字,表示在类路径下;
 *      classes:指定注解类所在的位置;
 *  备注:当我们使用5.x版本的时候,junit的jar必须是4.12以上;
 */
@RunWith()
@ContextConfiguration(classes = )
public class AccountServiceTest {
//    private ApplicationContext ac;
    @Autowired
    private IAccountService as;
    @Before
    public void init(){
        //1、获取容器
//        ac = new ClassPathXmlApplicationContext("bean.xml");
//        ac = new AnnotationConfigApplicationContext();
        //2、得到业务层对象
//        as = ac.getBean("accountService", );
    }
    @Before
    public void end(){
//        ();
    }
    @Test
    public void testFindAllAccount(){
        //、执行方法
        List<Account> accounts = as.findAllAccount();
        //4、遍历输出
        for (Account account : accounts) {
            println(account);
        }
    }
    @Test
    public void testFindAccountById(){
        Account account = as.findAccountById(1);
        println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setame("大哥");
        account.setMoney(2000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        Account account = new Account();
        account.setId();
        account.setame("二哥");
        account.setMoney(000);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        as.deleteAccountById(1);
    }
    //转账测试
    @Test
    public void testTransfer(){
        ("二哥","bbb",500);
    }
}
文件位置图:
备注:

其他文件见G005Spring学习笔记-Spring完全注解实现及优化;

发现问题:
代码语言:javascript代码运行次数:0运行复制
    //转账
    @Override
    public void transfer(String sourceame, String targetame, float money) {
        //1、根据名称查询转出账户;
        Account source = accountDao.findAccountByame(sourceame);
        //2、根据名称查询转入账户;
        Account target = accountDao.findAccountByame(targetame);
        //、转出账户减钱;
        source.setMoney(source.getMoney()-money);
        //4、转入账户加钱;
        target.setMoney(target.getMoney()+money);
        //5、更新转出账户;
        accountDao.updateAccount(source);

        //在这写一个错误,会导致转账过程中转出账户钱减了,但是转入账户钱没加
        int i = 1/0;

        //6、更新转入账户;
        accountDao.updateAccount(target);
    }
分析问题:
解决问题:

进行事务控制;

代码示例:

AccountServiceImpl:

代码语言:javascript代码运行次数:0运行复制
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) {
         = txManager;
    }

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

    @Override
    public List<Account> findAllAccount() {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            List<Account> accounts = accountDao.findAllAccount();
            //.提交事务
            txManagermit();
            //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);
            //.提交事务
            txManagermit();
            //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);
            //.提交事务
            txManagermit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void updateAccount(Account account) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            accountDao.updateAccount(account);
            //.提交事务
            txManagermit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void deleteAccount(Integer acccountId) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            accountDao.deleteAccount(acccountId);
            //.提交事务
            txManagermit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void transfer(String sourceame, String targetame, Float money) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作

            //2.1根据名称查询转出账户
            Account source = accountDao.findAccountByame(sourceame);
            //2.2根据名称查询转入账户
            Account target = accountDao.findAccountByame(targetame);
            //2.转出账户减钱
            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);
            //.提交事务
            txManagermit();

        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
            e.printStackTrace();
        }finally {
            //5.释放连接
            txManager.release();
        }


    }
}

ConnectionUtils连接工具类:

代码语言:javascript代码运行次数:0运行复制
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) {
                //.从数据源中获取一个连接,并且存入ThreadLocal中
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            //4.返回当前线程上的连接
            return conn;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 把连接和线程解绑
     */
    public void removeConnection(){
        tl.remove();
    }
}

TransactionManager事务工具类:

代码语言:javascript代码运行次数:0运行复制
package com.itheima.utils;

/**
 * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;

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

    /**
     * 开启事务
     */
    public  void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public  void commit(){
        try {
            connectionUtils.getThreadConnection()mit();
        }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配置文件:

代码语言:javascript代码运行次数:0运行复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=";
       xmlns:xsi=";
       xsi:schemaLocation="
        .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.apachem.dbutils.QueryRunner" scope="prototype"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:06/eesy"/>
        <property name="user" value="root"/>
        <property name="password" value="124"/>
    </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限制厂家的接口:

代码语言:javascript代码运行次数:0运行复制
package com.zibo.proxy;

//对生产厂家要求的接口
public interface IProducer {

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

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

}

Producer厂家类:

代码语言:javascript代码运行次数:0运行复制
package com.zibo.proxy;

//生产者
public class Producer implements IProducer {

    //销售
    public void saleProduct(float money){
        println("销售产品,拿到钱" + money);
    }

    //售后
    public void afterService(float money){
        println("提供售后服务,并拿到钱" + money);
    }

}

Client模拟顾客类:

代码语言:javascript代码运行次数:0运行复制
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)(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.getame())){
                    returnValue = method.invoke(producer,money * 0.8f);
                }
                return returnValue;
            }
        });
        proxyProducer.saleProduct(10000f);
    }
}
文件位置图:
运行结果:

2、简单案例(基于子类的动态代理)

改造的代码:

Client:

代码语言:javascript代码运行次数:0运行复制
package com.;

 import net.proxy.Enhancer;
import net.proxy.MethodInterceptor;
import net.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)(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.getame())){
                    returnValue = method.invoke(producer,money * 0.8f);
                }
                return returnValue;
            }
        });
        cglibProducer.saleProduct(12000f);
    }
}

Producer:

代码语言:javascript代码运行次数:0运行复制
package com.;

//生产者
public class Producer {

    //销售
    public void saleProduct(float money){
        println("销售产品,拿到钱" + money);
    }

    //售后
    public void afterService(float money){
        println("提供售后服务,并拿到钱" + money);
    }

}

pom.xml配置文件:

代码语言:javascript代码运行次数:0运行复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0"
         xmlns:xsi=";
         xsi:schemaLocation=".0.0 .0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId></groupId>
    <artifactId>spring09</artifactId>
    <version>1.0-SAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_</version>
        </dependency>
    </dependencies>


</project>
文件位置图:
运行结果:
四、使用动态代理实现事务控制

代码:

BeanFactory:

代码语言:javascript代码运行次数:0运行复制
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) {
         = txManager;
    }


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

    /**
     * 获取Service代理对象
     * @return
     */
    public IAccountService getAccountService() {
        return (IAccountService)(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.getame())){
                            return method.invoke(accountService,args);
                        }

                        Object rtValue = null;
                        try {
                            //1.开启事务
                            txManager.beginTransaction();
                            //2.执行操作
                            rtValue = method.invoke(accountService, args);
                            //.提交事务
                            txManagermit();
                            //4.返回结果
                            return rtValue;
                        } catch (Exception e) {
                            //5.回滚操作
                            txManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            //6.释放连接
                            txManager.release();
                        }
                    }
                });

    }
}

AccountServiceTest:

代码语言:javascript代码运行次数:0运行复制
package com.;

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.ContextConfiguration;
import org.junit4.SpringJUnit4ClassRunner;

/**
 * 使用Junit单元测试:测试我们的配置
 */
@RunWith()
@ContextConfiguration(locati = "classpath:bean.xml")
public class AccountServiceTest {

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

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

}

AccountServiceImpl:

代码语言:javascript代码运行次数:0运行复制
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 sourceame, String targetame, Float money) {
        println("transfer....");
            //2.1根据名称查询转出账户
            Account source = accountDao.findAccountByame(sourceame);
            //2.2根据名称查询转入账户
            Account target = accountDao.findAccountByame(targetame);
            //2.转出账户减钱
            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:

代码语言:javascript代码运行次数:0运行复制
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) {
         = txManager;
    }


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

    /**
     * 获取Service代理对象
     * @return
     */
    public IAccountService getAccountService() {
        return (IAccountService)(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.getame())){
                            return method.invoke(accountService,args);
                        }

                        Object rtValue = null;
                        try {
                            //1.开启事务
                            txManager.beginTransaction();
                            //2.执行操作
                            rtValue = method.invoke(accountService, args);
                            //.提交事务
                            txManagermit();
                            //4.返回结果
                            return rtValue;
                        } catch (Exception e) {
                            //5.回滚操作
                            txManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            //6.释放连接
                            txManager.release();
                        }
                    }
                });

    }
}

文件位置图:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-01-06,如有侵权请联系 cloudcommunity@tencent 删除接口事务学习笔记ioc代理

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/biancheng/1199183.html

相关标签:无
上传时间: 2025-07-23 14:32:08
留言与评论(共有 13 条评论)
本站网友 搜狐ceo
19分钟前 发表
原始发表:2025-01-06
本站网友 run播放器
10分钟前 发表
如果结果超过一个抛异常 */ Account findAccountByame(String accountame); }接口实现类AccountDaoImpl:代码语言:javascript代码运行次数:0运行复制package com.zibo.dao.impl; import com.zibo.dao.IAccountDao; import com.zibo.domain.Account; import org.apachem.dbutils.QueryRunner; import org.apachem.dbutils.handlers.BeanHandler; import org.apachem.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"
本站网友 燕麦片粥
20分钟前 发表
"bbb"
本站网友 中医治疗青春痘
28分钟前 发表
转出账户减钱; source.setMoney(source.getMoney()-money); //4
本站网友 子宫内膜
24分钟前 发表
account.getame()
本站网友 单县电影网
20分钟前 发表
加上classpath关键字
本站网友 字体大宝库
26分钟前 发表
account.getMoney()); }catch (Exception e){ throw new RuntimeException(e); } } @Override public void updateAccount(Account account) { try { runner.update("update account set name = ?
本站网友 无性症候群
26分钟前 发表
args); } Object rtValue = null; try { //1.开启事务 txManager.beginTransaction(); //2.执行操作 rtValue = method.invoke(accountService
本站网友 中医治疗脱发
8分钟前 发表
mysql
本站网友 奎文区公众信息网
19分钟前 发表
分享自作者个人站点/博客
本站网友 鸡肉的营养价值
23分钟前 发表
mysql
本站网友 b2b系统
21分钟前 发表
Object[] args) throws Throwable { if("test".equals(method.getame())){ return method.invoke(accountService