【spring(二)Spring中的Aop--基于xml配置】

问题的提出

客户的业务层实现类
/**
* 账户的业务层实现类
* @author 黑马程序员
* @Company http://www.ithiema.com
* @Version 1.0
*/
public class AccountServiceImpl implements IAccountService {
	private IAccountDao accountDao;
	public void setAccountDao(IAccountDao accountDao) {
		this.accountDao = accountDao;
	}
	@Override
	public void saveAccount(Account account) throws SQLException {
		accountDao.save(account);
	}
	@Override
	public void updateAccount(Account account) throws SQLException{
		accountDao.update(account);
	}
	@Override
	public void deleteAccount(Integer accountId) throws SQLException{
		accountDao.delete(accountId);
	}
	@Override
	public Account findAccountById(Integer accountId) throws SQLException {
		return accountDao.findById(accountId);
	}
	@Override
	public List<Account> findAllAccount() throws SQLException{
		return accountDao.findAll();
	}
}

问题就是:
事务被自动控制了。换言之,我们使用了 connection 对象的 setAutoCommit(true)
此方式控制事务,如果我们每次都执行一条 sql 语句,没有问题,但是如果业务方法一次要执行多条 sql语句,这种方式就无法实现功能了。

请看下面的示例:
我们在业务层中多加入一个方法。
业务层接口


/**
* 转账
* @param sourceName
* @param targetName
* @param money
*/
void transfer(String sourceName,String targetName,Float money);
业务层实现类:
@Override
public void transfer(String sourceName, String targetName, Float money) {
	//根据名称查询两个账户信息
	Account source = accountDao.findByName(sourceName);
	Account target = accountDao.findByName(targetName);
	//转出账户减钱,转入账户加钱
	source.setMoney(source.getMoney()-money);
	target.setMoney(target.getMoney()+money);
	//更新两个账户
	accountDao.update(source);
	int i=1/0; //模拟转账异常
	accountDao.update(target);
}

当我们执行时,由于执行有异常,转账失败。但是因为我们是每次执行持久层方法都是独立事务,导致无法实现事务控制( 不符合事务的一致性)

解决办法:
  让业务层来控制事务的提交和回滚。

改造后的业务层实现类:
用 注:此处没有使用 spring 的 的 IoC.
/**
* 账户的业务层实现类
* @author 黑马程序员
* @Company http://www.ithiema.com
* @Version 1.0
*/
public class AccountServiceImpl implements IAccountService {
	private IAccountDao accountDao = new AccountDaoImpl();
	@Override
	public void saveAccount(Account account) {
		try {
			TransactionManager.beginTransaction();
			accountDao.save(account);
			TransactionManager.commit();
		} catch (Exception e) {
			TransactionManager.rollback();
			e.printStackTrace();
		}finally {
			TransactionManager.release();
			} 
		}
	@Override
	public void updateAccount(Account account) {
		try {
		TransactionManager.beginTransaction();
		accountDao.update(account);
		TransactionManager.commit();
		} catch (Exception e) {
		TransactionManager.rollback();
		e.printStackTrace();
		}finally {
			TransactionManager.release();
		}
	}
	@Override
	public void deleteAccount(Integer accountId) {
		try {
			TransactionManager.beginTransaction();
			accountDao.delete(accountId);
			TransactionManager.commit();
		} catch (Exception e) {
			TransactionManager.rollback();
			e.printStackTrace();
		}finally {
			TransactionManager.release();
		}
}
	@Override
	public Account findAccountById(Integer accountId) {
		Account account = null;
	try {
		TransactionManager.beginTransaction();
		account = accountDao.findById(accountId);
		TransactionManager.commit();
		return account;
	} catch (Exception e) {
		TransactionManager.rollback();
		e.printStackTrace();
	}finally {
		TransactionManager.release();
	}
		return null;
	}
	@Override
	public List<Account> findAllAccount() {
		List<Account> accounts = null;
		try {
			TransactionManager.beginTransaction();
			accounts = accountDao.findAll();
			TransactionManager.commit();
			return accounts;
		} catch (Exception e) {
			TransactionManager.rollback();
			e.printStackTrace();
		}finally {
			TransactionManager.release();
		}
			return null;
	}
	@Override
	public void transfer(String sourceName, String targetName, Float money) {
		try {
			TransactionManager.beginTransaction();
			Account source = accountDao.findByName(sourceName);
			Account target = accountDao.findByName(targetName);
			source.setMoney(source.getMoney()-money);
			target.setMoney(target.getMoney()+money);
			accountDao.update(source);
			int i=1/0;
		accountDao.update(target);
		TransactionManager.commit();
	} catch (Exception e) {
		TransactionManager.rollback();
		e.printStackTrace();
	}finally {
		TransactionManager.release();
			}
		}
	}

	TransactionManager  类的代码:
	/**
	* 事务控制类
	* @author 黑马程序员
	* @Company http://www.ithiema.com
	* @Version 1.0
	*/
	public class TransactionManager {
		//定义一个 DBAssit
		private static DBAssit dbAssit = new DBAssit(C3P0Utils.getDataSource(),true);
		//开启事务
		public static void beginTransaction() {
		try {
			dbAssit.getCurrentConnection().setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
			}
		}
		//提交事务
		public static void commit() {
		try {
			dbAssit.getCurrentConnection().commit();
		} catch (SQLException e) {
			e.printStackTrace();
			}
		}
		//回滚事务
		public static void rollback() {
		try {
			dbAssit.getCurrentConnection().rollback();
			} catch (SQLException e) {
				e.printStackTrace();
				}
			}
			//释放资源
			public static void release() {
			try {
				dbAssit.releaseConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
}

新的问题
 业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。
试想一下,如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。
解决方案就是使用动态代理的技术
动态代理的特点:

字节码随用随创建,随用随加载。
它与静态代理的区别也在于此。因为静态代理是字节码一上来就创建好,并完成加载。
装饰者模式就是静态代理的一种体现。

动态代理常用的有两种方式

基于接口的动态代理
	提供者:JDK 官方的 Proxy 类。
	要求:被代理类最少实现一个接口。
基于子类的动态代理
	提供者:第三方的 CGLib,如果报 asmxxxx 异常,需要导入 asm.jar。
	要求:被代理类不能用 final 修饰的类(最终类)。

使用JDK官方的Proxy 类创建代理对象

此处我们使用的是一个演员的例子:
在很久以前,演员和剧组都是直接见面联系的。没有中间人环节。
而随着时间的推移,产生了一个新兴职业:经纪人(中间人),这个时候剧组再想找演员就需要通过经纪
人来找了。下面我们就用代码演示出来。
/**
* 一个经纪公司的要求:
* 能做基本的表演和危险的表演
*/
public interface IActor {
	/**
	* 基本演出
	* @param money
	*/
	public void basicAct(float money);
	/**
	* 危险演出
	* @param money
	*/
	public void dangerAct(float money);
	}
	/**
	* 一个演员
	*/
	//实现了接口,就表示具有接口中的方法实现。即:符合经纪公司的要求
public class Actor implements IActor{
	public void basicAct(float money){
		System.out.println("拿到钱,开始基本的表演:"+money);
	}
	public void dangerAct(float money){
		System.out.println("拿到钱,开始危险的表演:"+money);
	}
}
public class Client {
	public static void main(String[] args) {
	//一个剧组找演员:
		final Actor actor = new Actor();//直接
		/**
		* 代理:
		* 	间接。
		* 获取代理对象:
			* 要求:
				* 被代理类最少实现一个接口
		* 创建的方式
			* Proxy.newProxyInstance(三个参数)
		* 参数含义:
		* ClassLoader:和被代理对象使用相同的类加载器。
		* Interfaces:和被代理对象具有相同的行为。实现相同的接口。
		* InvocationHandler:如何代理。
		* 策略模式:使用场景是:
						* 数据有了,目的明确。
						* 如何达成目标,就是策略。
		*
		*/
		IActor proxyActor = (IActor) Proxy.newProxyInstance(
										actor.getClass().getClassLoader(),
										actor.getClass().getInterfaces(),
										new InvocationHandler() {
							/**
							* 执行被代理对象的任何方法,都会经过该方法。
							* 此方法有拦截的功能。
							*
							* 参数:
							* proxy:代理对象的引用。不一定每次都用得到
							* method:当前执行的方法对象
							* args:执行方法所需的参数
							* 返回值:
							* 当前执行方法的返回值
							*/
							@Override
							public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
								String name = method.getName();
								Float money = (Float) args[0];
								Object rtValue = null;
									//每个经纪公司对不同演出收费不一样,此处开始判断
										if("basicAct".equals(name)){
											//基本演出,没有 2000 不演
											if(money > 2000){
											//看上去剧组是给了 8000,实际到演员手里只有 4000
											//这就是我们没有修改原来 basicAct 方法源码,对方法进行了增强
											rtValue = method.invoke(actor, money/2);
								}
							}
								if("dangerAct".equals(name)){
									//危险演出,没有 5000 不演
									if(money > 5000){
									//看上去剧组是给了 50000,实际到演员手里只有 25000
									//这就是我们没有修改原来 dangerAct 方法源码,对方法进行了增强
									rtValue = method.invoke(actor, money/2);
									}
								}
									return rtValue;
								}
						});
							//没有经纪公司的时候,直接找演员。
							// actor.basicAct(1000f);
							// actor.dangerAct(5000f);
							//剧组无法直接联系演员,而是由经纪公司找的演员
							proxyActor.basicAct(8000f);
							proxyActor.dangerAct(50000f);
			}
}

使用 CGLib 的 的 Enhancer 类创建代理对象

还是那个演员的例子,只不过不让他实现接口。
/**
* 一个演员
*/
public class Actor{//没有实现任何接口
	public void basicAct(float money){
		System.out.println("拿到钱,开始基本的表演:"+money);
	}
	public void dangerAct(float money){
		System.out.println("拿到钱,开始危险的表演:"+money);
		}
}
public class Client {
	/**
	* 基于子类的动态代理
	* 要求:
	* 被代理对象不能是最终类
	* 用到的类:
	* Enhancer
	* 用到的方法:
	* create(Class, Callback)
	* 方法的参数:
	* Class:被代理对象的字节码
	* Callback:如何代理
	* @param args
	*/
	public static void main(String[] args) {
		final Actor actor = new Actor();
		Actor cglibActor = (Actor) Enhancer.create(actor.getClass(),
			new MethodInterceptor() {
		/**
		* 执行被代理对象的任何方法,都会经过该方法。在此方法内部就可以对被代理对象的任何
		方法进行增强。
		*
		* 参数:
		* 前三个和基于接口的动态代理是一样的。
		* MethodProxy:当前执行方法的代理对象。
		* 返回值:
		* 当前执行方法的返回值
		*/
		@Override
		public Object intercept(Object proxy, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
			String name = method.getName();
			Float money = (Float) args[0];
			Object rtValue = null;
		if("basicAct".equals(name)){
			//基本演出
			if(money > 2000){
				rtValue = method.invoke(actor, money/2);
			}
		}
		if("dangerAct".equals(name)){
		//危险演出
		if(money > 5000){
			rtValue = method.invoke(actor, money/2);
			}
		}
		return rtValue;
			}
		});
	cglibActor.basicAct(10000);
	cglibActor.dangerAct(100000);
	}
}

回到最开始的业务层:

/**
* 用于创建客户业务层对象工厂(当然也可以创建其他业务层对象,只不过我们此处不做那么繁琐)
* @author 黑马程序员
* @Company http://www.ithiema.com
* @Version 1.0
*/
public class BeanFactory {
/**
* 创建账户业务层实现类的代理对象
* @return
*/
public static IAccountService getAccountService() {
		//1.定义被代理对象
		final IAccountService accountService = new AccountServiceImpl();
		//2.创建代理对象
		IAccountService  proxyAccountService  =  (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),accountService.getClass().getInterfaces(),
			new	InvocationHandler() {
				/**
				* 执行被代理对象的任何方法,都会经过该方法。
				* 此处添加事务控制
				*/
			@Override
			public Object invoke(Object proxy, Method method,Object[] args) throws Throwable {
					Object rtValue = null;
					try {
							//开启事务
							TransactionManager.beginTransaction();
							//执行业务层方法
							rtValue = method.invoke(accountService, args);
							//提交事务
							TransactionManager.commit();
						}catch(Exception e) {
							//回滚事务
							TransactionManager.rollback();
							e.printStackTrace();
						}finally {
							//释放资源
							TransactionManager.release();
					}
					return rtValue;
					}
					});
					return proxyAccountService;
}
}

当我们改造完成之后,业务层用于控制事务的重复代码就都可以删掉了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值