我爱编程

《Spring实战》笔记(三):AOP

2018-04-12  本文已影响0人  JacobY

1 AOP术语

AOP的术语主要有如下几个:

  1. 通知
    在AOP术语中,切面的工作被称为通知。通知定义了切面是什么以及何时使用。除了描述切面要完成的工作,通知还解决了何时执行这个工作的问题。
    Spring切面可以应用5种类型的通知:
  1. 连接点
    连接点是在应用执行过程中能够插入切面的一个点。这个点可以是调用方法时、抛出异常时、甚至修改一个字段时。切面代码可以利用这些点插入到应用的正常流程之中,并添加新的行为。
  2. 切点
    如果说通知定义了切面的“什么”和“何时”的话,那么切点就定义了“何处”。切点的定义会匹配通知所要织入的一个或多个连接点。
  3. 切面
    切面是通知和切点的结合。通知和切点共同定义了切面的全部内容——它是什么,在何时和何处完成其功能。
  4. 引入
    引入允许我们向现有的类添加新方法或属性。
  5. 织入
    织入是把切面应用到目标对象并创建新的代理对象的过程。切面在指定的连接点被织入到目标对象中。在目标对象的生命周期里有多个点可以进行织入:

2 Spring AOP 简介

Spring提供了4种类型的AOP支持:

Spring AOP的特点:

3 切点的编写

Spring AOP支持的AspectJ切点指示器.JPG

其中最为常用的是exection(),其使用方法为:

exection()使用方法.JPG
还可以使用&&, ||, !等操作符,在XML中,则以and, or, not来表示。
匹配指定包下所有的方法:execution("* com.demo.controller.*(..))
匹配指定包以及其子包下的所有方法:execution("* com.demo..*(..)")
选择特定的bean(bean()使用bean ID或bean名称作为参数来限制切点只匹配特定的bean):exection(* concert.Performance.perform(..) && bean('woodstock'))

4 定义切面

声明通知的注解.JPG
@Aspect
public class HelloAspect {

    @Pointcut("execution(* me.ye.springinaction.controller.Controller.hello(..))")
    public void hello() {}

    @Before("hello()")
    public void beforeHello() {
        System.out.println("ready for hello");
    }

    @AfterReturning("hello()")
    public void afterHello() {
        System.out.println("after hello");
    }

    @AfterThrowing("hello()")
    public void errorWhenHello() {
        System.out.println("error when hello");
    }

}

可以使用@Pointcut来定义切点,也可以直接在通知的注解中直接以切点的表达式作为参数。
定义了切面之后,还要注入相应的bean,以及在配置类中启用自动代理@EnableAspectJAutoProxy

@ComponentScan
@Configuration
@EnableAspectJAutoProxy
public class AspectConfig {
    @Bean
    public HelloAspect helloAspect() {
        return new HelloAspect();
    }
}

@Around的用法:

public class HelloAspect {

    @Pointcut("execution(* me.ye.springinaction.controller.Controller.hello(..))")
    public void hello() {}

    @Around("hello()")
    public void helloAspect(ProceedingJoinPoint joinPoint) {

        try {
            System.out.println("ready for hello");
            joinPoint.proceed();
            System.out.println("after hello");
        } catch(Throwable ex) {
            System.out.println("error when hello");
        }
    }
}

当要将控制权交给被通知的方法时,需要调用ProceedingJoinPoint的proceed()方法。

5 通过切面引入新功能

切面还可以为bean添加来自其他接口的方法,而并不需要真正实现其他接口。通过代理,引入其他接口,当调用到引入接口的方法时,代理会将调用委托给实现了该接口的其他对象。


使用Spring AOP为bean引入新的方法.JPG
@Aspect
public class DeclareParentsAspect {

    @DeclareParents(value = "me.ye.springinaction.service.DemoService", defaultImpl = CommonParentImpl.class)
    private CommonParent commonParent;
}

@DeclareParents注解由三部分组成:

使用的时候可以将bean进行类型转换为要引入的接口,再调用要引入的方法即可。

((CommonParent)service).doSomething();
上一篇 下一篇

猜你喜欢

热点阅读