《Spring5框架》AOP

1. AOP概念

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

2. AOP(底层原理)

AOP 底层使用动态代理
有两种情况动态代理:

  • 第一种 有接口情况,使用 JDK 动态代理
    创建接口实现类代理对象,增强类的方法

  • 第二种 没有接口情况,使用 CGLIB 动态代理
    创建子类的代理对象,增强类的方法

3. AOP(JDK 动态代理)

  代理:是一种常用的设计模式,其目的就是为其他对象提供一个代理以控制对某个对象的访问。
1、使用 JDK 动态代理,使用 Proxy 类里面的方法创建代理对象

  • 调用 newProxyInstance 方法
static Object newProxyInstance(ClassLoaderloader, Class[] interfaces, InvocationHandler h)

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

  • Interface InvocationHandler接口:该接口中定义了一个方法:
public object invoke(Object obj,Method method, Object[] args)

第一参数,代理类
第二参数,被代理的方法
第三参数,参数数组。
这个抽象方法在代理类中动态实现。

4. JDK动态代理代码示例

动态代理步骤:
1.创建一个实现接口InvocationHandler的类,且实现invoke方法
2.创建被代理的类以及接口
3.通过Proxy的静态方法newProxyInstance创建一个代理
4.通过代理调用方法

  • 需要动态代理的接口:
/**
 * 需要动态代理的接口
 */
public interface UserDao {
    public String SayHello(String name);
}
  • 需要代理的实际对象
public class UserDaoImpl implements UserDao{

    @Override
    public String SayHello(String name) {
        return "hello " + name;
    }
}
  • 创建代理对象代码
public class UserDaoProxy implements InvocationHandler {

    /**
     * 把创建的是谁的代理对象,把谁传递过来
     */
    private Object userdao;

    /**
     * 构造方法,给要代理的真实对象赋初值
     * @param userdao
     */
    public UserDaoProxy(Object userdao) {
        this.userdao = userdao;
    }

    /**
     *
     * @param proxy:代理类实例
     * @param method:被调用的方法对象
     * @param args:调用参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //在代理真实对象前可以添加一些其他的操作
        System.out.println("方法之前执行...."+method.getName()+" ;传递的参数..."+ Arrays.toString(args));
        //被增强的方法执行
        Object res = method.invoke(userdao, args);
        //在代理真实对象后可以添加一些其他的操作
        System.out.println("方法之后执行...."+userdao);
        return res;
    }
}
  • 使用 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));
        String tom = dao.SayHello("Tom");
        System.out.println(tom);
    }
}

实验结果:
在这里插入图片描述

5. AOP一些术语

  • 连接点:
    类里面哪些方法可以被增强,这些方法称为连接点

  • 切入点:
    实际被真正增强的方法,称为切入点

  • 通知(增强)
    实际增强的逻辑部分称为通知(增强)
    通知有多种类型:
     前置通知
     后置通知
     环绕通知
     异常通知
     最终通知

  • 切面:
    把通知应用到切入点的过程

6. AOP 操作(准备工作)

  • 1、Spring 框架一般都是基于 AspectJ 实现 AOP 操作
      AspectJ 不是 Spring 组成部分,而是独立 的AOP 框架,一般把 AspectJ 和 Spirng 框架一起使用,进行 AOP 操作。

  • 2、基于 AspectJ 实现 AOP 操作
      基于 xml 配置文件实现
      基于注解方式实现(使用)

  • 3、在项目工程里面引入 AOP 相关依赖
    在这里插入图片描述

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

权限修饰符一般为:*,表示任意权限修饰符;
返回类型可以省略;

举例1:对 test08.UserDao 类里面的SayHello进行增强

execution(* test08.User.SayHello(..))

举例 2:对 test08.UserDao 类里面的所有的方法进行增强

execution(* test08.UserDao .* (..))

举例 3:对 test08 包里面所有类,类里面所有方法进行增强

execution(* test08.*.* (..))

7. AOP 操作(AspectJ 注解)

1、创建类,在类里面定义方法

//被增强的类
@Component//实现bean的注入
public class User {
    public void walk(){
        System.out.println("user walk......");
    }
}

2、创建增强类(编写增强逻辑)
在增强类里面,创建方法,让不同方法代表不同通知类型
在增强类上面添加注解 @Aspect

@Component//实现bean的注入
@Aspect //生成代理对象
public class UserProxy {
    //前置通知
    //@Before 注解表示作为前置通知
    @Before(value = "execution(* test09.User.walk(..))")
    public void before(){
        System.out.println("before......");
    }
}

3、进行通知的配置
在 spring 配置文件中,开启注解扫描
在 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="test09"></context:component-scan>
<!--开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

测试类:

public class UserTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test09/bean.xml");
        User user = context.getBean("user", User.class);
        user.walk();
    }
}

实验结果:
在这里插入图片描述

8. 不同类型的通知如何配置

在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
 //前置通知
 //@Before 注解表示作为前置通知
 @Before(value = "execution(* test09.User.walk(..))")
 public void before() {
 System.out.println("before.........");
 }
 //后置通知(返回通知)
 @AfterReturning(value = "execution(* test09.User.walk(..))")
 public void afterReturning() {
 System.out.println("afterReturning.........");
 }
 //最终通知
 @After(value = "execution(* test09.User.walk(..))")
 public void after() {
 System.out.println("after.........");
 }
 //异常通知
 @AfterThrowing(value = "execution(* test09.User.walk(..))")
 public void afterThrowing() {
 System.out.println("afterThrowing.........");
 }
 //环绕通知
 @Around(value = "execution(* test09.User.walk(..))")
 public void around(ProceedingJoinPoint proceedingJoinPoint) throws 
Throwable {
 System.out.println("环绕之前.........");
 
 //被增强的方法执行
 proceedingJoinPoint.proceed();
 
 System.out.println("环绕之后.........");
 } }

8.1 相同的切入点抽取

当切入点表达式相同时,可以抽取出来,公用。

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

8.2 设置增强类优先级

有多个增强类对同一个方法进行增强,设置增强类优先级
在增强类上面添加注解 @Order(数字类型值)数字类型值越小优先级越高

@Component
@Aspect
@Order(1)
public class PersonProxy

9. 完全使用注解开发

创建配置类,不需要创建 xml 配置文件

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

测试类:

public class test {
    @Test
    public void test(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigAop.class);
        User user = context.getBean("user", User.class);
        user.walk();
    }
}

实验结果:
在这里插入图片描述

10. AOP 操作(AspectJ 配置文件)

被增强类:

public class User {
    public void walk(){
        System.out.println("user walk......");
    }
}

增强类:

public class UserProxy {
    //前置通知
    //@Before 注解表示作为前置通知
    @Before(value = "execution(* test09.User.walk(..))")
    public void before(){
        System.out.println("before......");
    }
}

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: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="user" class="test09.User"></bean>
  <bean id="userProxy" class="test09.UserProxy"></bean>

    <!--配置 aop 增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(*
test09.User.walk(..))"/>
        <!--配置切面-->
        <aop:aspect ref="userProxy">
            <aop:before method="before" pointcut-ref="p"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

测试类:

public class UserTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test09/bean.xml");
        User user = context.getBean("user", User.class);
        user.walk();
    }
}

实验结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值