SrpingBoot与AOP

首先,创建一个简单的Spring Boot应用。

其次,引入AOP依赖,在pom文件中添加spring-boot-starter-aop。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

编写一个切面类:

@Configuration
@Aspect
public class AOPConfig {
    @Around("@within(org.springframework.stereotype.Controller)")
    public Object simpleAop(final ProceedingJoinPoint pjp) throws Throwable {
        try {
            Object[] args = pjp.getArgs();
            System.out.println("args:" + Arrays.asList(args));
            //调用原来的方法
            Object o = pjp.proceed();
            System.out.println("return:" + o);
            return o;
        } catch (Throwable e) {
            throw e;
        }
    }
}
  • @Configuration,声明这是一个Spring配置类。

  • @Aspect,声明这是一个切面类。

  • @Around,声明一个表达式,描述要织入的目标的特性,比如@within表示目标类型带有注解,其注解类型为org.springframework.stereotype.Controller,这意味着Spring Controller方法被调用时,都会执行@Around标注的方法,也就是simpleAop。

  • simpleAop,用来织入的代码,其参数ProceedingJoinPoint,如上述实例,将调用方法的参数取出来打印到控制台。

  • pjp.proceed,通常情况下,执行完切面代码还需要继续执行应用代码,proceed()方法会继续调用原有的业务逻辑,并将返回对象正常返回。

  • 继续执行应用代码,有可能抛出异常,在切面里,我们不会处理这个异常,直接抛给调用者。

Spring Aop支持多种表达式及表达式的组合,一些简单的表达式如下。

  • execution(public * *(..)) 所有public方法,星号代表类路径、方法名。

  • execution(* set*(..)) 所有set开头的方法。

  • execution(public set*(..)) 所有set开头的public方法。

  • execution(public com.xyz.entity* set*(..)) 所有set开头的public方法,且位于com.xyz.entity包下。

  • target(com.xyz.service.CommonService) 所有实现了CommonService接口的类的方法。

  • @target(org.springframework.transaction.annotation.Transactional) 所有用@Transactional注解的方法。

  • @within(org.springframework.stereotype.Controller) 声明了@Controller的所有方法。

<<SpringBoot 2 从构建小系统到分布式大系统>>

猜你喜欢

转载自www.cnblogs.com/asleaf/p/12730888.html
AOP
今日推荐