前置内容:请查看参考文章关于Spring AOP 的讲解
补充说明Spring AOP 的切点描述方式说明如下:
Spring AOP支持在切点表达式中使用如下的切点指示符:
-
execution匹配方法执行的连接点,这是你将会用到的Spring的最主要的切点指示符。 -
within限定匹配特定类型的连接点(在使用Spring AOP的时候,在匹配的类型中定义的方法的执行)。 -
this限定匹配特定的连接点(使用Spring AOP的时候方法的执行),其中bean reference(Spring AOP 代理)是指定类型的实例。 -
target限定匹配特定的连接点(使用Spring AOP的时候方法的执行),其中目标对象(被代理的应用对象)是指定类型的实例。 -
args限定匹配特定的连接点(使用Spring AOP的时候方法的执行),其中参数是指定类型的实例。 -
@target限定匹配特定的连接点(使用Spring AOP的时候方法的执行),其中正执行对象的类持有指定类型的注解。 -
@args限定匹配特定的连接点(使用Spring AOP的时候方法的执行),其中实际传入参数的运行时类型持有指定类型的注解。 -
@within限定匹配特定的连接点,其中连接点所在类型已指定注解(在使用Spring AOP的时候,所执行的方法所在类型已指定注解)。 -
@annotation限定匹配特定的连接点(使用Spring AOP的时候方法的执行),其中连接点的主题持有指定的注解。
Spring Boot 中对AOP有相应的整合自动配置,所以可以不需要进行相应的配置。关于拦截@Get请求,在了解Spring AOP的切点指示符规则后,本案例需要进行拦截项目中的@Get请求,所以选用@annotation的切点指示符进行切点描述。
- pom.xml中进行Spring AOP的引入
<!--spring aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
- 创建一个
Aspect(切面)声明类,用于描述Pointcut(切点)及Advice(增强)。
package com.jaghand.bss.taurus.base.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author jaghand
* @version V1.0
* @date 2019/3/28 1:33
*/
@Aspect
@Component
public class BssUserGetFunAspect {
/**
* 配置切点
*/
@Pointcut("@annotation(javax.ws.rs.GET)")
public void pointCut() {
}
/**
* 通知
*/
/**
* 前置通知
* @param joinPoint 连接点
*/
@Before("pointCut()")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("前置通知");
}
/**
* 后置通知
* @param joinPoint
*/
@After("pointCut()")
public void afterAdvice(JoinPoint joinPoint) {
System.out.println("后置通知");
}
}
在@annotation(javax.ws.rs.GET)中直接对需要拦截的@Get注解进行配置,自定义注解则配置自定注解路径。至此对@Get注解的拦截已经完成。
- 创建Controller控制类进行请求测试
package com.jaghand.bss.taurus.base.controller;
import com.jaghand.bss.taurus.base.service.IBssUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
@Component
@Path("users")
public class BssUserController {
@Autowired
private IBssUserService iBssUserService;
@Path("/")
@GET
public String getUserById(@QueryParam("userId") String userId){
return "success1";
}
}
客户端访问路径:http://localhost:9001/users
- 控制台打印结果
前置通知
后置通知