Spring AOP 概述

2 篇文章 0 订阅

Spring AOP 应用场景

AOP 是 OOP 的延续,是 Aspect Oriented Programming 的缩写,意思是面向切面编程。可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP设计模式孜孜不倦追求的是调用者和被调用这之间的解耦,AOP 可以说也是这种目标的一种实现。

我们现在做的一些非业务,如:日志、事务、安全等都会写在业务代码中(也即是说,这些非业务类横切与业务类),但这些代码往往是重复,复制-粘贴式的代码会给程序带来不便,AOP 就实现了把这些业务与需求分开来做。这种解决的方式也成代理机制。

AOP 中必须明白的几个概念

1、切面(Aspect)

​ 官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”。

​ 连接点( Joinpoint ) :程序执行过程中的某一行为,例如, MemberService.get 的调用或者 MemberService.delete 抛出异常等行为。

2、通知(Advice)

​ “切面”对于某个 “连接点” 所产生的动作。其中,一个 “切面” 可以包含多个 “Advice” 。

3、切入点(Pointcut)

​ 匹配连接点的断言,在 AOP 中通知和一个切入点表达式关联。切面中的所有通知所关注的连接点,都由切入点表达式来决定。

4、目标对象(Target Object)

​ 被一个或者多个切面所通知的对象。例如, AServiceImpl 和 BServiceImpl ,当然在实际运行时,Spring AOp 采用代理实现, 实际

AOP 操作的是 TargetObject 的代理对象。

5、AOP 代理(AOP Proxy)

​ 在 Spring AOP 中有两种代理方式, JDK 动态代理和 CGLib 代理。默认情况下, TargetObject 实现了接口时,则采用 JDK 动态代理,

例如 AServiceImpl ;反之,才有CGLib代理,例如,BServiceImpl。强制使用 CGLib 代理需要将的 proxy-target-class 属性设为 true。

以下是通知(Advice)类型:

6、前置通知(Before Advice)

​ 在某连接点 ( JoinPoint )之前执行的通知,但这个通知不能组织连接点前的执行。 ApplicationContext 在<aop:aspect>里面使用

<aop:before>元素进行声明。

7、后置通知(After Advice)

​ 当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。 ApplicationContext 中在 <aop:aspect>里面使用

<aop:after>元素进行声明。

8、返回后通知 (After Return Advice)

​ 在某连接带你正常完成后执行的通知,不包括抛出异常的情况。 ApplicationContext 中再 <aop:aspect> 里面使用

<after-returning>元素进行声明。

9、环绕通知(Around Advice)

​ 包围一个连接点的通知,类似 Web 中 Servlet 规范中的 Filter 的 doFilter 方法。可以再方法的调用前后完成自定义的行为,也可以选

择不执行。 ApplicationContext 中在 <aop:aspect>里面使用<aop:around> 元素进行声明。

10、异常通知 (After Throwing Advice)

​ 在方法抛出异常退出时执行的通知。ApplicationContext 中在 <aop:aspect> 里面使用 <aop:after-throwing> 元素进行声明。

注:可以将多个通知应用到一个目标对象上,既可以将多个织面织入到同一个目标对象

AOP 使用示例:

AnnotaionAspect:

//声明这是一个组件
@Component
//声明这是一个切面 Bean
@Aspect
public class AnnotaionAspect {

    private final static Logger log = Logger.getLogger(AnnotaionAspect.class);

    //配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点
    //service包下所有类的方法
    @Pointcut("execution(* com.example.aopdemo.aop.service..*(..))")
    public void aspect(){ }

    /*
     * 配置前置通知,使用在方法 aspect()上注册的切入点
     * 同时接受 JoinPoint 切入点对象,可以没有该参数
     */
    @Before("aspect()")
    public void before(JoinPoint joinPoint) {
        log.info("before 通知 " + joinPoint);
    }

    //配置后置通知,使用在方法 aspect()上注册的切入点
    @After("aspect()")
    public void after(JoinPoint joinPoint){
        log.info("after 通知 " + joinPoint);
    }

    //配置环绕通知,使用在方法 aspect()上注册的切入点
    @Around("aspect()")
    public void around(JoinPoint joinPoint){
        long start = System.currentTimeMillis();
        try {
            ((ProceedingJoinPoint) joinPoint).proceed();
            long end = System.currentTimeMillis();
            log.info("around 通知 " + joinPoint + "\tUse time : " + (end - start) + " ms!");
        } catch (Throwable e) {
            long end = System.currentTimeMillis();
            log.info("around 通知 " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : "
                    + e.getMessage());
        }
    }

    //配置后置返回通知,使用在方法 aspect()上注册的切入点
    @AfterReturning("aspect()")
    public void afterReturn(JoinPoint joinPoint){
        log.info("afterReturn 通知 " + joinPoint);
    }

    //配置抛出异常后通知,使用在方法 aspect()上注册的切入点
    @AfterThrowing(pointcut="aspect()", throwing="ex")
    public void afterThrow(JoinPoint joinPoint, Exception ex){
        log.info("afterThrow 通知 " + joinPoint + "\t" + ex.getMessage());
    }


}

AnnotationTester 测试调用:

@ContextConfiguration(locations = {"classpath*:application-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class AnnotationTester {

    @Autowired
    MemberService annotationService;
   /* @Autowired
    ApplicationContext app;*/
    @Test
    // @Ignore
    public void test(){
        System.out.println("=====这是一条华丽的分割线======");
        annotationService.save(new Member());
        System.out.println("=====这是一条华丽的分割线======");
        try {
            annotationService.delete(1L);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

}

调用结果如下::

=====这是一条华丽的分割线======
com.example.aopdemo.aop.AnnotaionAspect@491b9b8
2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] before 通知 execution(void com.example.aopdemo.aop.service.MemberService.save(Member))
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] save member method . . .
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] around 通知 execution(void com.example.aopdemo.aop.service.MemberService.save(Member))	Use time : 16 ms!
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] afterReturn 通知 execution(void com.example.aopdemo.aop.service.MemberService.save(Member))
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] after 通知 execution(void com.example.aopdemo.aop.service.MemberService.save(Member))
  =====这是一条华丽的分割线======
2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] before 通知 execution(boolean com.example.aopdemo.aop.service.MemberService.delete(long))
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] delete method . . .
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] around 通知 execution(boolean com.example.aopdemo.aop.service.MemberService.delete(long))	Use time : 1 ms with exception : spring aop ThrowAdvice演示
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] afterReturn 通知 execution(boolean com.example.aopdemo.aop.service.MemberService.delete(long))
  2022-03-06 14:12:06 [INFO]-[com.example.aopdemo.aop.AnnotaionAspect] after 通知 execution(boolean com.example.aopdemo.aop.service.MemberService.delete(long))
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值