Spring—AOP三种实现方式(JDK动态代理与CGLIB动态代理)

目录

  • Spring—Aop
    • 一、通过 Spring API 接口实现
    • 二、自定义类来实现Aop
    • 三、使用注解实现
  • 动态代理(JDK动态代理与CGLIB动态代理)

Spring—Aop

提供声明式事务;允许用户自定义切面

以下名词需要了解下:

  • 横切关注点:跨越应用程序多个模块的方法或功能。
  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。它是一个类。
  • 通知(Advice):切面必须要完成的工作。它是类中的一个方法。
  • 目标(Target):被通知对象。它是一个接口或者是一个方法
  • 代理(Proxy):向目标对象应用通知之后创建的对象。它是代理类
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

SpringAOP中,通过Advice可以定义横切逻辑,支持5种类型

通知类型 连接点 实现接口
前置通知 方法前 org.springframework.aop.MethodBeforeAdvice
后置通知 方法后 org.springframework.aop.AfterReturningAdvice
环绕通知 方法前后 org.aopalliance.intercept.MethodInterceptor
异常抛出通知 方法抛出异常 org.springframework.aop.ThrowsAdvice
引介通知 类中添加新的方法属性 org.springframeword.aop.IntroductionInterceptor

使用Sping实现Aop需要导入一个依赖包

    <dependencies>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.6version>
        dependency>
    dependencies>

一、通过 Spring API 接口实现

  1. 编写抽象角色与真实角色
//抽象角色
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();

}
//真实角色
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("添加用户");
    }

    public void delete() {
        System.out.println("删除用户");
    }

    public void update() {
        System.out.println("修改用户");
    }

    public void query() {
        System.out.println("查询用户");
    }
}
  1. 编写日志
    编写两个日志, 前置增强与后置增强
//前置增强
public class log implements MethodBeforeAdvice {
    //method: 要执行的目标对象方法
    //args:参数
    //target: 目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
//后置增强
public class AfterLog implements AfterReturningAdvice {
   //returnValue 返回值
   //method被调用的方法
   //args 被调用的方法的对象的参数
   //target 被调用的目标对象
   @Override
   public void afterReturning(Object returnValue, Method method, Object[] args,Object target) throws Throwable {
       System.out.println("执行了" + target.getClass().getName()
       +"的"+method.getName()+"方法,"
       +"返回值:"+returnValue);
  }
}
  1. 将类都注册到spring中 , 并实现aop切入实现 , 注意导入约束

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="userService" class="com.it04.service.UserServiceImpl"/>
    <bean id="log" class="com.it04.log.log"/>
    <bean id="afterLog" class="com.it04.log.AfterLog"/>

    
    
    <aop:config>
        
        <aop:pointcut id="pointcut" expression="execution(* com.it04.service.UserServiceImpl.*(..))"/>
        
        
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    aop:config>

beans>
  1. 测试
public class MyTest {
    public static void main(String[] args) {
        //获取类路径下的xml文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //默认的JDK动态代理是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

二、自定义类来实现Aop

  1. 自己的编写一个切入类
public class DiyPointcut {

   public void before(){
       System.out.println("---------方法执行前---------");
  }
   public void after(){
       System.out.println("---------方法执行后---------");
  }
   
}
  1. 在Spring中进行配置

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="userService" class="com.it04.service.UserServiceImpl"/>
    <bean id="log" class="com.it04.log.log"/>
    <bean id="afterLog" class="com.it04.log.AfterLog"/>
    
    
    <bean id="diy" class="com.it04.diy.DiyPointcut"/>

    
    <aop:config>
        
        
        <aop:aspect ref="diy">
            
            <aop:pointcut id="point" expression="execution(* com.it04.service.UserServiceImpl.*(..))"/>
            
            
            <aop:before method="before" pointcut-ref="point" />
            <aop:after method="after" pointcut-ref="point" />
        aop:aspect>
    aop:config>
beans>
  1. 测试不变
public class MyTest {
    public static void main(String[] args) {
        //获取类路径下的xml文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //默认的JDK动态代理是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

三、使用注解实现

  1. 编写一个注解实现的类
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//标准这个类是一个切面
@Aspect
public class AnnotationPointcut {
   @Before("execution(* com.it04.service.UserServiceImpl.*(..))")
   public void before(){
       System.out.println("---------方法执行前---------");
  }

   @After("execution(* com.it04.service.UserServiceImpl.*(..))")
   public void after(){
       System.out.println("---------方法执行后---------");
  }

}
  1. 在Spring中开启注解支持

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="userService" class="com.it04.service.UserServiceImpl"/>
    <bean id="log" class="com.it04.log.log"/>
    <bean id="afterLog" class="com.it04.log.AfterLog"/>
    

    
    <bean id="annotationPointcut" class="com.it04.diy.AnnotationPointcut"/>
    
    <aop:aspectj-autoproxy/>
beans>
  1. 测试不变
public class MyTest {
    public static void main(String[] args) {
        //获取类路径下的xml文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //默认的JDK动态代理是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

动态代理(JDK动态代理与CGLIB动态代理)

在开启注解支持的时候有一个值
proxy-target-class=""
默认为false是JDK动态代理,基于接口实现
设置为true是CDLIB动态代理,基于类实现

    
    <bean id="annotationPointcut" class="com.it04.diy.AnnotationPointcut"/>
    
    <aop:aspectj-autoproxy/>

JDK动态代理

  • JDK 动态代理只提供接口的代理,不支持类的代理。

  • 核心InvocationHandler 接口和 Proxy 类,InvocationHandler 通过 invoke()方法

  • 反射来调用目标类中的代码,动态地将横切逻辑和业务编织在一起;

  • 接着,Proxy利用 InvocationHandler 动态创建一个符合某一接口的的实例, 生成目标类的代理对象。

CGLIB动态代理

  • 如果代理类没有实现 InvocationHandler 接口,那么 Spring AOP 会选择使用 CGLIB 来动态代理目标类。

  • CGLIB(Code Generation Library),是一个代码生成的类库,可以在运行时动态的生成指定类的一个子类对象,并覆盖其中特定方法并添加增强代码,从而实现 AOP。

  • CGLIB 是通过继承的方式做的动态代理,因此如果某个类被标记为 final,那么它是无法使用 CGLIB 做动态代理的。

你可能感兴趣的:(Spring,spring,aop)