溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Boot學習入門之AOP處理請求詳解

發布時間:2020-10-03 02:04:28 來源:腳本之家 閱讀:183 作者:a60782885 欄目:編程語言

前言

面向切面(AOP)Aspect Oriented Programming是一種編程范式,與語言無關,是一種程序設計思想,它也是spring的兩大核心之一。

在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等信息。

如果我們想要獲取當前正在攔截的方法的信息??梢允褂肑oinPoint。

例如:

@After("pointcut1()") 
public void after(JoinPoint joinPoint) { 
 logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName()); 
 System.out.println("after"); 
} 

就可以獲取包名,類名,方法名。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女