• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

java 搞代码 4年前 (2022-01-05) 27次浏览 已收录 0个评论

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术,下面这篇来源gao($daima.com搞@代@#码(网文章主要给大家介绍了关于Spring Boot学习入门之AOP处理请求的相关资料,需要的朋友可以参考下。

前言

面向切面(AOP)Aspect Oriented Programming是一种编程范式,与语言无关,是一种程序设计思想,它也是spring的两大核心之一。

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

首先加入依赖关系:

  org.springframework.bootspring-boot-starter-aop

希望截拦如下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"); } 

就可以获取包名,类名,方法名。

总结

以上就是Spring Boot学习入门之AOP处理请求详解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Spring Boot学习入门之AOP处理请求详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址