Java AOP详解以及在Spring中的运用

AOP简介

来自百度百科对AOP的解释:
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP使用了动态代理技术,动态代理技术的一个特点就是在不修改源码的基础上对已有方法进行增强。简而言之,AOP思想就是把程序中的重复代码提取出来,在需要执行这部分代码的时候,使用动态代理技术,在不修改源码的基础上,对已有方法进行增强。

AOP的作用:

  • 在运行期间,在不修改源码的基础上,对已有方法进行增强
    AOP的优点:
  • 减少重复代码
  • 提高开发效率
  • 方便维护

预编译又称为预处理,是做些代码文本的替换工作。是整个编译过程的最先做的工作。
.
《Java 动态代理详解以及在Spring事务控制中的使用案例》

在《Java 动态代理详解以及在Spring事务控制中的使用案例》中说到动态代理有两种方式:基于接口的方式和基于子类的方式,基于接口的方式要求被代理对象至少实现一个接口,基于子类的方式要求被代理类不能是最终类。在Spring中,框架会根据目标类是否实现了接口来决定采用哪种动态代理方式。

AOP相关术语:

为了帮助理解下面这些术语,我再将《Java 动态代理详解以及在Spring事务控制中的使用案例》中的案例代码贴出来:

/**
 * 用于创建Service的代理对象的工厂
 */
public class BeanFactory {

    private IAccountService accountService;
    private TransactionManager txManager;

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

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

    public IAccountService getAccountService() {
        //执行accountService中的任何方法都会经过该方法
        return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    //执行service层方法时都会经过该方法
                    @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 {
                        	//开启事务
                            txManager.beginTransaction();
							
							//执行代理的方法
                            rtValue = method.invoke(accountService, args);

							//提交事务
                            txManager.commitTransaction();

                            return rtValue;
                        } catch (SQLException e) {
                            try {
                            	//回滚事务
                                txManager.rollbackTransaction();
                            } catch (SQLException ex) {
                                ex.printStackTrace();
                            }
                        } finally {
                            try {
                            	//释放数据库连接资源到数据库池中
                                txManager.releaseTransaction();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }

                        return null;
                    }
                });
    }
}
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

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

    public void transfer(String sourceName, String targetName, Float money) {
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDao.updateAccount(source);
        accountDao.updateAccount(target);
    }
}
  • Joinpoint(连接点)
    连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的
    连接点。
    【也就是IAccountService 接口提供的所有方法】

  • Pointcut(切入点)
    指我们要对哪些 Joinpoint 进行拦截的定义。
    【就是getAccountService方法中注释“这里比之前的代码多加入三行”这个地方,说明除了test方法之外,其他IAccountService方法都会被增强,所以除了test方法之外,其他方法都是切入点】

  • Advice(通知/增强)
    所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
    【通知就是拦截之后要做的事情,比如开启事务,提交事务等。上面的示例代码中,通知是由TransactionManager类提供的方法】
    通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
    整个invoke方法在执行就是环绕通知在这里插入图片描述

  • Introduction(引介)
    引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field。

  • Target(目标对象)
    代理的目标对象。
    【accountService对象,也就是被代理对象——AccountServiceImpl类的对象】

  • Weaving(织入)
    是指把增强应用到目标对象来创建新的代理对象的过程。
    【即上面代码中try{…}catch(){…}finally{…}中对被代理对象方法进行增强而产生新的代理对象的过程】
    spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。

  • Proxy(代理)
    一个类被 AOP 织入增强后,就产生一个结果代理类。
    【也就是代理对象,即return (IAccountService) Proxy.newProxyInstance(…),返回的代理对象】

  • Aspect(切面)
    是切入点和通知(引介)的结合。
    【即切入点方法和通知方法之间的逻辑关系】

Spring框架的AOP执行机制

当开发人员编写好业务核心代码,把公共代码抽取出来,制作成通知,再配置切入点和通知之间的逻辑关系,即切面之后,在程序运行阶段,Spring框架监控切入点方法的执行。一旦监控到切入点方法被执行,就使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

Spring中基于XML的AOP示例

目录结构:
在这里插入图片描述
导入坐标:

<!--用于解析切入点表达式-->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
</dependency>

业务层接口:

public interface IAccountService {
    void saveAccount();

    void updateAccount(int i);

    int deleteAccount();

}

业务层接口的实现类:

public class AccountServiceImpl implements IAccountService {
    public void saveAccount() {
        System.out.println("save");
        
    }

    public void updateAccount(int i) {
        System.out.println("upate--"+i);

    }

    public int deleteAccount() {
        System.out.println("delete");
        return 0;
    }
}

用一个Logger类来模拟通知,计划让切入点方法执行之前打日志“log”:

public class Logger {
    /**
     * 用于打日志:计划让其在切入点方法执行之前执行
     */
    public void printLog() {
        System.out.println("log");

    }
}

在bean.xml中配置AOP:

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置Spring的IOC容器-->
    <bean id="accountService" class="com.example.service.impl.AccountServiceImpl"></bean>

    <!--Spring基于xml的AOP配置
        1. 把通知Bean交给spring管理
        2. 使用aop:config标签表明开始AOP的配置
        3. 使用aop:aspect标签表明配置切面
            ref属性指通知类bean的id
        4. 在aop:aspect标签的内部使用对应的标签来配置通知的类型
            pointcut属性:用于指定【切入点表达式】,该表达式的指的是对业务中的那些方法增强
            切入点表达式的写法:
                关键字:execution(表达式)
                表达式格式:访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
                          或者:用"*"表示通配
    -->

    <!--配置logger-->
    <bean id="logger" class="com.example.utils.Logger"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--配置通知类型,并且建立通知方法和切入点方法的关联-->
            <!-- <aop:before method="printLog" pointcut="execution(public void com.example.service.impl.AccountServiceImpl.saveAccount())"></aop:before>-->

            <!--或者用下面这种方式配置通知类型-->
            <aop:before method="printLog" pointcut-ref="pt1"></aop:before>

            <!--配置切入点表达式-->
            <aop:pointcut id="pt1" expression="execution(* *..*.*(..))"/>
        </aop:aspect>
    </aop:config>
</beans>

测试:

public class AOPTest {
    public static void main(String[] args) {
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService)ac.getBean("accountService");
        as.saveAccount();
        as.deleteAccount();
        as.updateAccount(1);
    }
}

结果:

log
save
log
delete
log
upate--1

切入点表达式的写法

            
关键字:execution(表达式)
表达式:
    访问修饰符  返回值  包名.包名.包名...类名.方法名(参数列表)
标准的表达式写法:
    public void com.example.service.impl.AccountServiceImpl.saveAccount()
访问修饰符可以省略
    void com.example.service.impl.AccountServiceImpl.saveAccount()
返回值可以使用通配符,表示任意返回值
    * com.example.service.impl.AccountServiceImpl.saveAccount()
包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*.
    * *.*.*.*.AccountServiceImpl.saveAccount())
包名可以使用..表示当前包及其子包
    * *..AccountServiceImpl.saveAccount()
类名和方法名都可以使用*来实现通配
    * *..*.*()
参数列表:
    可以直接写数据类型:
        基本类型直接写名称         int
        引用类型写包名.类名的方式   java.lang.String
    可以使用通配符表示任意类型,但是必须有参数
    可以使用..表示有无参数均可,有参数可以是任意类型
全通配写法:
    * *..*.*(..)

实际开发中切入点表达式的通常写法:
    切到业务层实现类下的所有方法
        * com.example.service.impl.*.*(..)
参数列表:
    可以直接写数据类型:
        基本类型直接写名称           int
        引用类型写包名.类名的方式   java.lang.String
    可以使用通配符表示任意类型,但是必须有参数
    可以使用..表示有无参数均可,有参数可以是任意类型
全通配写法:
    * *..*.*(..)

实际开发中切入点表达式的通常写法:
    切到业务层实现类下的所有方法
        * com.example.service.impl.*.*(..)

四种通知类型

<!--pt1指的是切入点表达式-->
<!-- 配置前置通知:在切入点方法执行之前执行-->
<aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>

<!-- 配置后置通知:在切入点方法正常执行之后执行-->
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>

<!-- 配置异常通知:在切入点方法执行产生异常之后执行-->
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>

<!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行-->
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>

Spring中基于注解的AOP示例

将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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.example"></context:component-scan>

    <!-- 配置spring开启注解AOP的支持 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

给AccountServiceImpl类打上@Service("accountService")注解
Logger类改为:

@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger2 {
    @Pointcut("execution(* com.example.service.impl.*.*(..))")
    private void pt1(){}

    /**
     * 前置通知
     */
    @Before("pt1()")
    public  void beforePrintLog(){
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
    }

    /**
     * 后置通知
     */
    @AfterReturning("pt1()")
    public  void afterReturningPrintLog(){
        System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
    }
    /**
     * 异常通知
     */
    @AfterThrowing("pt1()")
    public  void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
    }

    /**
     * 最终通知
     */
    @After("pt1()")
    public  void afterPrintLog(){
        System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
    }
}

结果:

前置通知Logger类中的beforePrintLog方法开始记录日志了。。。
save
最终通知Logger类中的afterPrintLog方法开始记录日志了。。。
后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。

在Spring框架中,有一个通知方法调用顺序的问题,上面的结果显示的是最终通知在后置通知执行前执行了。可以用环绕通知解决这个问题,Spring框架中的环绕通知为我们提供了一种可以在代码中手动控制增强方法何时执行的方式。

@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger2 {
    @Around("pt1()")
    public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//得到方法执行所需的参数

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");

            rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }
}

结果:

Logger类中的aroundPringLog方法开始记录日志了。。。前置
save
Logger类中的aroundPringLog方法开始记录日志了。。。后置
Logger类中的aroundPringLog方法开始记录日志了。。。最终

AOP原理简述

(1)每一个bean创建之前,调用postProcessBeforeInstantiation()方法,该方法主要执行:

  • 判断当前bean是否在adviseBeans中(保存了所有需要增强的bean)
  • 判断当前bean是否继承或实现Advice、Pointcut等或者是否打上了@Aspect注解(即判定当前bean是否是切面类)

(2)创建对象

  • 判定当前bean是需要增强
  • 如果当前bean需要增强获,取当前bean的所有增强器(通知方法)
  • 保存当前bean到adviseBeans中
  • 如果当前bean需要增强,创建当前bean的代理对象(由Spring自动决定是使用JDK动态代理还是cglib动态代理)
  • 给容器中返回当前组件使用动态代理增强了的代理对象
  • 以后从容器中获取到的就是这个组件的代理对象,执行目标方法的时候,代理对象就会执行通知方法的流程

至此,上面的例子中
IAccountService as = (IAccountService)ac.getBean("accountService"); as.saveAccount();
as是IAccountService的一个使用动态代理增强了的代理对象,当执行目标方法saveAccount()的时候,就进行代理过程

(3)执行目标方法

  • 执行目标方法的时,拦截器会进行拦截目标方法的执行
  • 拦截器中首先获取要执行的目标方法的拦截器链
  • 如果没有拦截器链,则直接执行目标方法;如果有拦截器链,把需要执行的目标对象、目标方法、拦截器链等信息放到一个对象中
  • 依次进入每一个拦截器进行执行:前置通知->目标方法->后置通知->返回通知或异常通知
发布了243 篇原创文章 · 获赞 87 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/IT_10/article/details/103838347
今日推荐