Spring5自学笔记_Real004(AOP(面向切面编程))

Spring5自学笔记_Real004(AOP(面向切面编程))

一、AOP面向切面编程(Aspect Oriented Programming)

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

在这里插入图片描述

二、AOP底层原理

1、AOP底层使用了动态代理。
(1)有两种情况的动态代理
第一种:有接口的情况,使用JDK动态代理
在这里插入图片描述
第二种:没有接口的情况,使用CGLIB动态代理
在这里插入图片描述

三、AOP中的JDK的动态代理

1、使用JDK动态代理,使用Poxy类里面的方法创建代理对象
用到的包:java.lang.reflect中有一个类叫做:Class Proxy
调用Class Proxy中的newProxyInstance方法

    @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h) {
        Objects.requireNonNull(h);
        final Class<?> caller = System.getSecurityManager() == null? null: Reflection.getCallerClass();

        /*
         * Look up or generate the designated proxy class and its constructor.
         */
        Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);

        return newProxyInstance(caller, cons, h);
    }

该方法右三个参数:
第一个参数:ClassLoader loader:类加载器;
第二个参数:Class<?>[] interfaces:由于这地方是JDK代理,所以需要接口,而这个参数就是被增强的类的实现的接口,增强方法所在的类,这个类实现的接口,支持多个接口;
第三个参数:InvocationHandler h:实现这个接口InvocationHandler,创建代理对象,写增强的方法

2、代码案例:

public interface UserDao {
    int Add(int a, int b);
    String UpdateId(String id);
}

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

    @Override
    public String UpdateId(String id) {
        return id;
    }
}

public class AOPProxy {

}

class UserDaoProxy implements InvocationHandler{

    //1、创建的是谁的代理对象,九八谁传进来
    //有参数的构造传递
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //被增强的方法之前执行
        System.out.println("方法之前执行..."+method.getName()+":传递的参数..."+ Arrays.toString(args));
        //被增强的方法执行
        Object res = method.invoke(obj, args);
        //被增强的方法之后执行
        System.out.println("方法之后执行..."+obj);
        return res;

    }
}

import com.SSMStudy.Spring5.AOPStudy.AOPDemo.AOPProxy;
import com.SSMStudy.Spring5.AOPStudy.AOPDemo.UserDao;
import com.SSMStudy.Spring5.AOPStudy.AOPDemo.UserDaoImp;

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

public class AOPTest {
    public static void main(String[] args) {
        Class[] interfaces = {UserDao.class};
//        Proxy.newProxyInstance(AOPProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                return null;
//            }
//        });
        UserDaoImp userDao = new UserDaoImp();
        UserDao dao = (UserDao) Proxy.newProxyInstance(AOPProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int res = dao.Add(1, 2);
        System.out.println(res);

    }
}
输出结果:
方法之前执行...Add:传递的参数...[1, 2]
方法之后执行...com.SSMStudy.Spring5.AOPStudy.AOPDemo.UserDaoImp@69d9c55
3

四、操作术语

在AOP面向切面编程中需要知道的几个主要的术语:
1、连接点:
类里面哪些方法可以被增强,这些方法称为连接点。
2、切入点:
实际被增强的方法,称为切入点。
3、通知(增强):
(1)实际增强的那一部分逻辑称为通知(增强)
(2)有多种类型:前置通知、后置通知、环绕通知、异常通知、最终通知
4、切面:
把通知应用到切入点的过程称为切面

五、AOP准备工作

1、Spring框架一般都是基于AspectJ实现AOP操作
(1)什么是AspectJ?
AspectJ不是Spring的一部分,他是单独的一个框架,一般把Spring与AspectJ一起使用,进行AOP操作
2、基于AspectJ实现AOP操作:
(1)基于XML配置文件实现
(2)基于注解方式实现(使用最多,因为比较方便)
3、引入相应的AOP依赖
在这里插入图片描述
4、切入点表达式
(1)切入点表达式的作用:直到对那个类里面的哪个方法进行增强。
(2)语法结构:
execution(【权限修饰符】【返回类型】【类全路径】.【方法名】(参数列表));
权限修饰符:public private … … 如果写" ∗ \ast “号代表任意的权限修饰符
返回类型:要增强的方法的返回值类型,可以不写返回值,void表示无返回值。
类的全路径:要增强的类的全路径
方法名:要增强的方法的方法名
参数列表:要增强的方法的参数列表,写两个点”…"表示原方法的参数列表的省略写法
举例1:对com.SpringTest.Dao.BookDao类里面的Add方法增强:
execution( ∗ \ast com.SpringTest.Dao.BookDao.Add(…));
举例2:对com.SpringTest.Dao.BookDao类里面的所有的方法进行增强
execution( ∗ \ast com.SpringTest.Dao.BookDao. ∗ \ast (…));
举例3:对com.SpringTest.Dao包中的所有类的所有方法进行增强
execution( ∗ \ast com.SpringTest.Dao. ∗ \ast . ∗ \ast (…));

六、基于注解方法进行AOP操作

1、创建类,在类中定义方法,作为被增强的类

public class Person {
    public void Add(){
        System.out.println("add... ...");
    }
}

2、创建一个增强类,编写增强的逻辑

/**
 * 用于增强的类
 */
public class PersonProxy {
    //前置通知
    public void Before(){
        System.out.println("before... ...");
    }
}

3、进行通知的配置
(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="com.SSMStudy.Spring5.AOPStudy.AOPAnno"></context:component-scan>
</beans>

(2)使用注解创建Person和User对象
在这里插入图片描述
在这里插入图片描述
(3)在增强类上面加上注解:@Aspect
在这里插入图片描述
(4)在Spring配置文件中开启生成代理对象
在XML配置文件加上:

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

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

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 用于增强的类
 */
@Component
@Aspect
public class PersonProxy {
    //前置通知
    //@Before注解表示该方法作为一个前置通知,注意@Before引入的包是org.aspectj.lang.annotation.Before;
    @Before(value="execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void Before(){
        System.out.println("before... ...");
    }
}

5、测试效果:

    @Test
    public void AOPTest01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
        Person person = context.getBean("person", Person.class);
        person.Add();
    }
输出结果:
before... ...
add... ...

物种通知类型的使用

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 用于增强的类
 */
@Component
@Aspect
public class PersonProxy {
    //前置通知
    //@Before注解表示该方法作为一个前置通知,注意@Before引入的包是org.aspectj.lang.annotation.Before;
    @Before(value="execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void Before(){
        System.out.println("before... ...");
    }

    //最终通知  在方法执行之后执行
    @After(value="execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void after(){
        System.out.println("after... ...");
    }

    //后置通知   在方法返回结果之后执行   有的书也叫做返回通知
    @AfterReturning(value="execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void afterReturning(){
        System.out.println("afterReturning... ...");
    }

    //异常通知
    @AfterThrowing(value="execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void afterThrowing(){
        System.out.println("afterThrowing... ...");
    }

    //环绕通知(在方法之前和之后都执行)
    @Around(value="execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("around之前... ...");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("around之后... ...");
    }
}

带入上面的运行测试程序的出输出结果:

around之前... ...
before... ...
add... ...
afterReturning... ...
after... ...
around之后... ...
注解方法AOP操作的两个细节问题

1、对公共的切入点进行提取/对相同切入点进行提取
在上述的例子中,我们会发现,增强部分的切入点都是相同的,即切入点表达式都是一样的,那么为了简化代码,我们可以将相同的哦切入点进行提取:
在增强类中添加PointDemo()方法,并添加注解@Pointcut(value = “execution(*.com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(…))”)
在增强方法上直接将注解value的值改为pointdemo()即可

    //相同切入点抽取
    @Pointcut(value = "execution(* com.SSMStudy.Spring5.AOPStudy.AOPAnno.Person.Add(..))")
    public void pointDemo(){}


    //前置通知
    //@Before注解表示该方法作为一个前置通知,注意@Before引入的包是org.aspectj.lang.annotation.Before;
    @Before(value="pointDemo()")
    public void Before(){
        System.out.println("before... ...");
    }

2、如果有多个增强类对同一个方法进行增强,我们可以设置增强类的优先级
(1)在增强类的上面添加注解@Order(数字类型),数字越小,优先级越高

七、基于配置文件方式进行AOP操作

1、准备工作,创建两个类,一个增强类,一个被增强的类

//被增强的类
public class Book {
    public void buy(){
        System.out.println("buy... ...");
    }
}
//增强的类
public class BookPoxy {
    public void before(){
        System.out.println("before... ...");
    }
}

2、在Spring配置文件中创建两个类的对象 3、在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
                            ">

    <!-- 创建两个类的对象 -->
    <bean id="book" class="com.SSMStudy.Spring5.AOPStudy.AOPXML.Book"></bean>
    <bean id="bookProxy" class="com.SSMStudy.Spring5.AOPStudy.AOPXML.BookPoxy"></bean>

    <!-- 配置AOP增强-->
    <aop:config>
        <!-- 切入点 -->
        <aop:pointcut id="p" expression="execution(* com.SSMStudy.Spring5.AOPStudy.AOPXML.Book.buy(..))"/>

        <!-- 配置切面 -->
        <aop:aspect ref="bookProxy">
            <!-- 怎很强作用在具体方法上 -->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>

    </aop:config>

</beans>

4、测试

    @Test
    public void AOPTestXML(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean6.xml");
        Book book = context.getBean("book", Book.class);
        book.buy();
    }
输出结果:
before... ...
buy... ...

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仲子_real

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值