springboot中使用aop技术
aop是面向切面编程的意思,它可以需要先选择一些切入点,然后对这些切入点进行拦截,注入统一的代码逻辑,这也是解耦的一种方式,也是为了避免重复的代码,让开发人员把关注点放在业务上。
引用包
'org.springframework.boot:spring-boot-starter-aop'
添加切入点
/**
* 基于com.lind.basic.controller包下的方法进行拦截.
*/
@Aspect
@Component
public class AopPrintConstController {
private static final Logger logger = LoggerFactory.getLogger(AopPrintConstController.class);
/**
* 横切点,哪些方法需要被横切.
*/
@Pointcut(value = "execution(public * com.lind.basic.controller..*.*(..))")
public void cutOffPoint() {
}
/**
* @param joinPoint 具体的方法之前执行.
*/
@Before("cutOffPoint()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
logger.info("cutOffPoint.before...");
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String requestURI = request.getRequestURI();
String remoteAddr = request.getRemoteAddr(); //这个方法取客户端ip"不够好"
String requestMethod = request.getMethod();
String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
logger.info("请求url=" + requestURI + ",客户端ip=" + remoteAddr + ",请求方式=" + requestMethod + ",请求的类名=" + declaringTypeName + ",方法名=" + methodName + ",入参=" + args);
}
/**
* 解用于获取方法的返回值.
*
* @param obj 返回值
*/
@AfterReturning(returning = "obj", pointcut = "cutOffPoint()")
public void doBefore(Object obj) throws Throwable {
logger.info("RESPONSE : " + obj);
}
}
测试
当我们访问controller下的接口下,在控制台中将输出方法执行前和执行后的结果
com.lind.basic.AopPrintConstController : 请求url=/hello/1,客户端ip=0:0:0:0:0:0:0:1,请求方式=GET,请求的类名=...
com.lind.basic.controller.H com.lind.basic.AopPrintConstController : RESPONSE : <200 OK,com.lind.basic.entity.Token@249f92d9,{}>
感想
事实上,springboot真的是一个强大的脚手架,它帮助我们把很多依赖都结合了,像今天说的aop,事实上springboot帮我们把以下包都结合在一起了,让开发人员引用时更方便。
springboot-aop集成了
- spring-aop,
- aspectjrt,
- spectjweaver
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2018-08-21 springboot~maven制作底层公用库
2018-08-21 我的那些年(9)~我来团队了,Mvc兴起了
2017-08-21 持续集成~Jenkins构建dotnetCore的项目