Spring AOP学习笔记

  本文是记录本人短暂学习Spring AOP的一些总结,由于本人能力有限,若存在问题还望指正。

 

  1、AOP的概念

    AOP的面向切面的编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而降低耦合度,提高程序可重用性和开发效率;将日志记录,事务处理,异常处理、性能统计,安全控制等代码从业务逻辑代码中划分出来,改变这些行为的时候不影响业务逻辑代码。简单来说,就是降低耦合度。

 

  2、AOP的原理

    AOP底层是使用了动态代理的模式,就JDK动态代理为例,代码如下:

class DynProxy {
    public static Object proxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),new MyInvocationHandler(obj));
    }
}

class MyInvocationHandler implements InvocationHandler{
    private final Object obj;

    public MyInvocationHandler(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
     System.out.println("Before");
return method.invoke(obj,args); } }

    DynProxy.proxy()传入obj对象,调用obj中的方法之前都会运行System.out.println("Before"); 因此,使用了动态代理的模式,可以大大的降低耦合度。

 

  3、AOP的术语

    (1)连接点:类里面可以被增强的方法。

    (2)切入点:实际被增强的方法。

    (3)通知(增强):实际增加的逻辑部分。( 通知有多种类型)

      • 前置通知
      • 后置通知
      • 环绕通知
      • 异常通知
      • 最终通知(finally)

    (4)切面:把通知应用到切入点的过程。

 

  4、AOP例子

    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">
  
   <!--开启注释扫描--> <context:component-scan base-package="com.study.day05"></context:component-scan>
   <!--开启Aspect生成代理对象--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>

    Java代码如下:

@Component
public class User {
    public void add() {
        System.out.println("创建");
    }
}

@Component
@Aspect
@Order(1)
public class UserProxy { @Before(value = "execution(* com.study.day05.User.add(..))") public void before() { System.out.println("before"); } } public class TestAnno { @Test public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml"); User user = context.getBean("user", User.class); user.add(); } }

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

 

posted on 2021-05-15 15:04  ustcwei  阅读(59)  评论(0)    收藏  举报