源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Spring Boot学习入门之AOP处理请求详解

  • 时间:2022-08-26 02:17 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Spring Boot学习入门之AOP处理请求详解
[b]前言[/b] 面向切面(AOP)Aspect Oriented Programming是一种编程范式,与语言无关,是一种程序设计思想,它也是spring的两大核心之一。 [b]在spring Boot中,如何用AOP实现拦截器呢?[/b] 首先加入依赖关系:
<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"); 
} 
就可以获取包名,类名,方法名。 [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部