AOP

什么是AOP

  面向切面编程(面向方面编程),利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
  通俗描述:可以在不修改源代码的基础上,在主干功能里面添加新功能。

AOP底层原理

AOP底层使用👉动态代理👈
第一种:有接口情况,使用JDK动态代理
实现方法:创建接口实现类代理对象,增强类的方法。
第二种:没有接口情况,使用CGLIB动态代理
实现方法:创建子类的代理对象,增强类的方法。


AOP(JDK动态代理)
JDK动态代理,使用Proxy类里面的方法创建代理对象。

调用Proxy类(结构如上图所示)当中的newProxyInstance方法创建代理对象。

static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) 
          返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。 

该方法有三个参数:
第一参数:类加载器
第二参数:增强方法所在的类,这个类实现的接口,支持多个接口
第三参数:实现这个接口InvocationHandler,创建代理对象,写增强的方法

底层代码实现过程:
(1)创建接口,定义方法

public interface UserDao {
    public int add(int a,int b);
}

(2)创建接口实现类,实现方法

public class UserDaoImpl implements UserDao{
    @Override
    public int add(int a, int b) {
        return a+b;
    }
}

(3)使用Proxy类创建接口代理对象

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类的代理对象
        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        //接口 = 实现类的代理对象
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler{
    /*把创建的是谁的代理对象,就把谁传递过来
    * 通过有参构造方法进行传递
    * 这里需要创建的就是UserDaoImpl的代理对象*/
    private UserDaoImpl userDao;
    public UserDaoProxy(UserDaoImpl userDao) {
        this.userDao = userDao;
    }
    //这里需要填写待增强的逻辑代码
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //模拟方法之前的执行操作
        System.out.println("方法之前执行...");
        //模拟被增强的方法执行
        Object res = method.invoke(userDao, args);
        //模拟方法之后的执行操作
        System.out.println("方法之后执行...");
        return res;
    }
}

AOP术语

  1. 连接点
    类里面哪些方法可以被增强,这些方法称为连接点。
  2. 切入点
    实际被真正增强的方法,称为切入点。
  3. 通知(增强)
    实际增强的逻辑部分称为通知(增强)。

通知有五种类型:

  • 前置通知@Before:在方法执行之前执行
  • 后置通知@After:在方法执行之后执行
  • 环绕通知@Around:围绕着方法执行
  • 异常通知@AfterThrowing:在方法抛出异常之后执行
  • 最终通知@AfterReturning:也叫返回通知,在方法返回结果之后执行
  1. 切面
    是一个动作,把通知应用到切入点的过程。

AOP操作实现

  1.Spring框架一般基于👉AspectJ👈实现AOP操作,那么什么是AspectJ呢?
  AspectJ并不是Spring组成部分,独立于AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作。
  2.基于AspectJ实现AOP操作
(1)基于xml配置文件实现
(2)基于注解方式实现
  3.在项目工程里面引入AOP相关依赖

  4.切入点表达式
(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构:
execution([权限修饰符] [返回类型] [类全路径] [方法名称] ([参数列表]))
举例1:对com.pf6668.dao.BookDao类里面的add方法进行增强

//权限修饰符可以直接使用*替代(代表任意的修饰符)
execution(* com.pf6668.dao.BookDao.add(..))

举例2:对com.pf6668.dao.BookDao类里面的所有方法进行增强

execution(* com.pf6668.dao.BookDao.*(..))

举例3:对com.pf6668.dao包里面的所有类、所有方法进行增强

execution(* com.pf6668.dao.*.*(..))

AOP操作(AspectJ注解)

第一步:创建类,在类里面定义方法

//需要被增强的类
public class User {
    public void add(){
        System.out.println("add...");
    }
}

第二步:创建增强类(编写增强逻辑)
(1)在增强类里面,创建方法,让不同的方法代表不同通知类型

//增强类
public class UserProxy {
    //模拟前置通知
    public void before(){
        System.out.println("before...");
    }
}

第三步:进行通知的配置
(1)在spring配置文件中,开启注解扫描

<?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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
     <!--开启注解扫描-->
    <context:component-scan base-package="aopanno"></context:component-scan>
</beans>

Tips:需要引入名称空间contextaop
(2)使用注解创建User、UserProxy对象


(3)在增强类上面添加注解@Aspect

(4)在spring配置文件中开启生成代理对象

 <!--开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

第四步:配置不同类型的通知
(1)在增强类里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

//增强类
@Component
@Aspect//生成代理对象
public class UserProxy {
    //模拟前置通知
    //@Before注解表示作为前置通知
    @Before(value = "execution(* aopanno.User.add(..))")
    public void before(){
        System.out.println("before...");
    }
}

(2)编写测试类进行模拟功能测试

public class Main {

    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        User user = context.getBean("user", User.class);
        user.add();
    }
}

运行结果如图所示:

关于其它几种通知的编写代码:

 //模拟后置通知
    @After(value = "execution(* aopanno.User.add(..))")
    public void after(){
        System.out.println("after..");
    }

    //模拟返回通知
    @AfterReturning(value = "execution(* aopanno.User.add(..))")
    public void afterReturning(){
        System.out.println("afterReturning..");
    }

    //模拟异常通知
    @AfterThrowing(value = "execution(* aopanno.User.add(..))")
    public void afterThrowing(){
        System.out.println("afterThrowing");
    }

    //模拟环绕通知
    @Around(value = "execution(* aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前....");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后....");
    }

第五步:可以进行公共切入点的提取(非必要步骤)

 //相同切入点的提取
    @Pointcut(value = "execution(* aopanno.User.add(..))")
    public void pointdemo(){
    }
     //模拟前置通知
    //@Before注解表示作为前置通知
    @Before(value = "pointdemo()")
    public void before(){
        System.out.println("before...");
    }

  如果存在多个增强类对同一个方法进行增强,可以设置增强类的优先级
解决方式:在增强类上面添加注解@Order(数字类型值),数值越小优先级越高。

  重点说明:上面的基于注解形式的AOP操作实际上有部分使用了xml配置文件,当然我们也可以采用基于完全注解的形式来进行AOP操作:
方法:采用一个配置类来代替xml配置文件当中的配置语句。实际上就是代替下面的两条语句:

    <!--开启注解扫描-->
    <context:component-scan base-package="aopanno"></context:component-scan>
    <!--开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

编写一个配置类ConfigAop

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackages = {"aopxml"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

@ComponentScan:开启注解扫描
@EnableAspectJAutoProxy:开启Aspect生成代理对象

AOP操作(AspectJ配置文件)

  在实际的项目开发中,很少使用基于配置文件的AOP操作,主要是基于注解的方式实现AOP操作。以下内容稍微了解即可…
第一步:创建两个类,增强类和被增强类,并且创建相应的方法

public class User {
    public void add(){
        System.out.println("add..");
    }
}
public class UserProxy {

    public void before(){
        System.out.println("before...");
    }
}

第二步:在spring配置文件中创建两个类对象

<bean id="user" class="aopxml.User"></bean>
<bean id="userProxy" class="aopxml.UserProxy"></bean>

第三步:在spring配置文件中配置切入点

<?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 https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--创建对象-->
    <bean id="user" class="aopxml.User"></bean>
    <bean id="userProxy" class="aopxml.UserProxy"></bean>
    
    <!--配置aop增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* aopxml.User.add(..))"/>
       <!-- 配置切面-->
        <aop:aspect ref="userProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
</beans>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值