Spring-xml实现AOP


AOP相关概念

Spring的AOP实现底层就是对上面的动态代理进行了封装。

  • Target(代理对象):代理的目标对象
  • Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类
  • Joinpoint(连接点):被拦截到的点(方法),spring只支持方法类型的连接点
  • Pointcut(切入点):指对哪些Joinpoint进行拦截的定义
  • Advice(通知/增强):拦截Joinpoint之后要做的事
  • Aspect(切面):切入点和通知的结合
  • Weaving(织入):指把增强应用到目标对象来创建新的代理对象的过程

xml实现AOP

1. 导入相关坐标

    
      org.springframework
      spring-context
      5.3.17
    
    
      org.aspectj
      aspectjweaver
      1.9.9
    

    
      org.springframework
      spring-test
      5.3.17
    
    
      junit
      junit
      4.13.2
      test
    

2. 创建目标接口和目标类(内部有切点)

package com.sjj.aop;

public interface TargetInterface {
    public void print_hello();
}
package com.sjj.aop;

public class Target implements TargetInterface{
    @Override
    public void print_hello() {
        System.out.println("HHHHHello");
    }
}

3. 创建切面类(内部有增强方法)

package com.sjj.aop;

public class MyAspect {
    public void before(){
        System.out.println("=====前置增强=====");
    }
}

4. 将目标类和切面类的对象创建权交给spring

    
    
    
    

5. 在appContext.xml中配置织入关系

    
    
        
        
            
            
        
    

6. 测试代码

package com.sjj.aop;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:appContext.xml")
public class AopTest {
    @Autowired
    private TargetInterface target;

    @Test
    public void test_aop01(){
        target.print_hello();
    }
}

配置解析

切点表达式

execution([修饰符] 返回值类型 包名.类名.方法名(参数))
  • 访问修饰符可省略
  • 返回值类型、包名、类名、方法名可用 * 表示任意
  • 包名和类之间的 . 表示当前包下的类。两个点 .. 表示包及其子包下的类
  • 参数列表可以使用 .. 表示任意个数任意类型的参数

所以你甚至可以这么写(bushi

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

通知


名称 标签 说明
前置 切入点方法之前
后置 切入点方法之后
环绕 切入点方法前后都执行
异常抛出 出现异常时执行
最终 最终通知,无论是否有异常都执行