Spring Boot學習入門之AOP處理請求詳解
前言
面向切面(AOP)Aspect Oriented Programming是一種編程范式,與語言無關,是一種程序設計思想,它也是spring的兩大核心之一。
在spring Boot中,如何用AOP實現(xiàn)攔截器呢?
首先加入依賴關系:
<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 "";
}
}
首先要創(chuàng)建一個攔截類: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等注解就非常輕松的實現(xiàn)截攔功能。
這里需要處理請求,所以我們需要在攔截器中獲取請求。
只需要在方法體中使用:
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");
}
就可以獲取包名,類名,方法名。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Java KindEditor粘貼圖片自動上傳到服務器功能實現(xiàn)
這篇文章主要介紹了Java KindEditor粘貼圖片自動上傳到服務器功能實現(xiàn),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
Java static方法用法實戰(zhàn)案例總結(jié)
這篇文章主要介紹了Java static方法用法,結(jié)合具體案例形式總結(jié)分析了java static方法功能、使用方法及相關操作注意事項,需要的朋友可以參考下2019-09-09
Spring使用RestTemplate和Junit單元測試的注意事項
這篇文章主要介紹了Spring使用RestTemplate和Junit單元測試的注意事項,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

