Spring Boot入门3——AOP处理请求

在Spring Boot中,如何用AOP实现拦截器呢?


首先加入依赖关系:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
希望截拦如下Controller:

@RestController
public class MyController {

	
	@RequestMapping(value="/hello", method=RequestMethod.GET)
	public String hello() {
		return "";
	}
	
}
首先要创建一个拦截类:RequestInterceptor

并且使用@Aspect和@Component标注这个类:

@Component
@Aspect
public class RequestInterceptor {
	
	@Pointcut("execution(* com.example.controller.*.*(..))")
	public void pointcut1() {}
	
	@Before("pointcut1()")
	public void doBefore() {
		System.out.println("before");
	}
	
	@Around("pointcut1()")
	public void around(ProceedingJoinPoint thisJoinPoint) throws Throwable {
		System.out.println("around1");
		thisJoinPoint.proceed();
		System.out.println("around2");
	}
	
	@After("pointcut1()")
	public void after(JoinPoint joinPoint) {
		System.out.println("after");
	}
	
	@AfterReturning("pointcut1()")
	public void afterReturning(JoinPoint joinPoint) {
		System.out.println("afterReturning");
	}
	
	@AfterThrowing("pointcut1()")
	public void afterThrowing(JoinPoint joinPoint) {
		System.out.println("afterThrowing");
	}
	
}
只需要使用@Before,@After等注解就非常轻松的实现截拦功能。


这里需要处理请求,所以我们需要在拦截器中获取请求。

只需要在方法体中使用:

ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest  request = attributes.getRequest();
就可以获取到request。

同理也可以在After等方法中获取response。

获取request之后,就可以通过request获取url,ip等信息。


如果我们想要获取当前正在拦截的方法的信息。可以使用JoinPoint。

例如:

@After("pointcut1()")
public void after(JoinPoint joinPoint) {
	logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName());
	System.out.println("after");
}
就可以获取包名,类名,方法名。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值