spring学习(三)

AOP

Aop作用:

  • 它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。
    能帮我们减少重复代码,提高开发效率,而且维护更方便。

AOP 的实现方式:

  • 使用动态代理技术

在上一篇博客做的增删改查例子中,客户的业务层实现类中存在一个问题。

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
语句,这种方式就无法实现功能了。

下面在业务层增加一个方法

业务层接口
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);
}

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

解决办法

让业务层来控制事务的提交和回滚。

//改造后的业务层
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 类的代码:
// 事务控制类

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 类创建代理对象

此处我们使用的是一个演员的例子:
在很久以前,演员和剧组都是直接见面联系的。没有中间人环节。
而随着时间的推移,产生了一个新兴职业:经纪人(中间人),这个时候剧组再想找演员就需要通过经纪
人来找了。下面我们就用代码演示出来。

/**
* 一个经纪公司的要求:
* 能做基本的表演和危险的表演
*/
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);
} }

了解动态代理后,来解决案例中的问题。

//用于创建客户业务层对象工厂
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; } }

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

Spring 中的 AOP

Aop配置步骤:

第一步:把通知类用 bean 标签配置起来

<bean id="accountService" class="zlb.demo02.service.impl.AccountServiceImpl"></bean>
 //通知类
  <bean id="logger" class="zlb.demo02.utils.Logger"></bean>

2 第二步:使用 aop:config 声明 aop 配置

aop:config:
作用:用于声明开始 aop 的配置
<aop:config>
<!-- 配置的代码都写在此处 -->
</aop:config>

第三步:使用 aop:aspect 配置切面

aop:aspect:
作用:
用于配置切面。
属性:
id:给切面提供一个唯一标识。
ref:引用配置好的通知类 bean 的 id。
 <aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型要写在此处-->
</aop:aspect>

4 第四步:使用 aop:pointcut 配置切入点表达式

aop:pointcut:
作用:
用于配置切入点表达式。就是指定对哪些类的哪些方法进行增强。
属性:
expression:用于定义切入点表达式。
id:用于给切入点表达式提供一个唯一标识

 <aop:pointcut id="pt" expression="execution(* zlb.demo02.service.impl.*.*(..))"/>

5 第五步:使用 aop:xxx 配置对应的通知类型

aop:before
作用:
用于配置前置通知。指定增强的方法在切入点方法之前执行
属性:
method:用于指定通知类中的增强方法名称
ponitcut-ref:用于指定切入点的表达式的引用
poinitcut:用于指定切入点表达式

aop:after-returning
作用:
用于配置后置通知

aop:after-throwing
作用:
用于配置异常通知

aop:after作用:
用于配置最终通知

环绕通知
作用:用于配置环绕通知属性:
method:指定通知中方法的名称。
pointct:定义切入点表达式pointcut-ref:指定切入点表达式的引用
说明:它是 spring 框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式。
注意:通常情况下,环绕通知都是独立使用的

 <aop:before method="beforePrint" pointcut-ref="pt"></aop:before>
         <aop:after-returning method="afterReturning" pointcut-ref="pt"></aop:after-returning>
         <aop:after-throwing method="afterThrowing" pointcut-ref="pt"></aop:after-throwing>
         <aop:after method="afterPrint" pointcut-ref="pt"></aop:after>
         <aop:around method="around" pointcut-ref="pt"></aop:around>
@Component
@Aspect
public class Logger {
   @Pointcut("execution(* zlb.demo02.service.impl.*.*(..))")
    public  void pt(){
    }
    @Before("pt()")
    public  void  beforePrint(){
        System.out.println("前置方法开始记录日志了");
    }
    @AfterReturning("pt()")
    public void afterReturning() {
        System.out.println("后置方法开始记录日志了");

    }
    @AfterThrowing("pt()")
    public  void  afterThrowing(){
        System.out.println("异常方法开始记录日志了");
    }
    @After("pt()")
    public  void  afterPrint(){
        System.out.println("最终方法开始记录日志了");
    }
//配置类
@Configuration
@ComponentScan(basePackages= "zlb.demo02")
@EnableAspectJAutoProxy //开启AOP注解扫描
public class ConfigClass {

}
//测试
public class AopTest {
    public static void main(String[] args){
        ApplicationContext context= new AnnotationConfigApplicationContext(ConfigClass.class);
      AccountService accountService=(AccountService) context.getBean("accountService");
      accountService.saveAccount();
    }
}

在这里插入图片描述

环绕通知单独测试

 //环绕通知
 @Around("pt()")
    public  Object  around(ProceedingJoinPoint point){
        System.out.println("前置方法开始记录日志了");
        Object value=null;
       try {
            Object [] args=point.getArgs();//明确调用业务层方法
            value = point.proceed(args);
           System.out.println("后置方法开始记录日志了");
        } catch (Throwable throwable) {
           System.out.println("异常方法开始记录日志了");
            throwable.printStackTrace();
        }finally {
           System.out.println("最终方法开始记录日志了");
        }

        return  value;
    }

在这里插入图片描述
通过对比发现通过注解配置,前面四个通知运行起来,顺序是有问题的(spring自身问题)
而使用环绕通知就不会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值