Spring Boot 之优雅使用 AOP

本文标题:Spring Boot 之优雅使用 AOP
原始链接: http://www.shuibo.cn/143.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。



简述何为AOP

AOP为Aspect Oriented Programming的缩写,意思是面向切面编程,通过预编译的方式和运行时动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑进行分离,降低耦合度,提高可重用性,提高开发效率。

主要用途
  1. 日志记录
  2. 事务处理
  3. 异常处理
  4. 安全处理
  5. 性能统计
    ···
在Spring Boot中使用AOP记录接口访问记录
1.添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.编写切面类
@Aspect // @Aspect切面类注解
@Component  // @Component把切面类加入到IOC容器中
public class ShuiBoAspect {

    private static final Logger logger = LoggerFactory.getLogger(ShuiBoAspect.class);

    public static long startTime;
    public static long endTime;

    /**
     * execution(public * cn.shuibo.controller.*.*(..))
     * 表示cn.shuibo.controller包下所有类的所有方法, "..."表示所有方法中的参数不限个数
     */
    @Pointcut("execution(public * cn.shuibo.controller.*.*(..))")
    public void shuiboPointcutLog(){

    }
    @Before("shuiboPointcutLog()")
    public void before(JoinPoint joinPoint) {
        startTime = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        HttpServletRequest request = requestAttributes.getRequest();
        Method method = signature.getMethod();
        String requestURI = request.getRequestURI();
        logger.info("请求URL:" + requestURI);
        String requestMethod = request.getMethod();
        logger.info("请求方式:" + requestMethod);
        Object[] args = joinPoint.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + "=" + args[i];
            }
            logger.info("入参:" + params);
        }
        String remoteAddr = request.getRemoteAddr();
        logger.info("IP:" + remoteAddr);
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        logger.info("类名:" + declaringTypeName);
        String methodName = joinPoint.getSignature().getName();
        logger.info("方法名:" + methodName);
    }

    @After("shuiboPointcutLog()")
    public void after() {
        endTime = System.currentTimeMillis() - startTime;
    }

    @AfterReturning(pointcut = "shuiboPointcutLog()", returning = "object")
    public void getAfterReturn(Object object) {
        logger.info("访问耗时:{}ms", endTime);
    }
}
3.编写测试类
@RestController
public class TestController {

    @GetMapping(value = "/index")
    public String index(String text){
        String shuibo = "shuibo.cn";
        if(shuibo.equals(text)){
            shuibo = "https://shuibo.cn";
        }else{
            shuibo = "http://shuibo.cn";
        }
        return shuibo;
    }
}
4.运行结果(控制台)
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 请求URL:http://localhost:8080/index
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 请求方式:GET
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 入参: text=1
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: IP:0:0:0:0:0:0:0:1
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 类名:cn.shuibo.controller.TestController
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 方法名:index
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 访问耗时:4ms
总结

通过以上实践,我们了解并学习了如何使用Spring Aop切面编程记录访问记录。
本文GitHub地址:https://github.com/ishuibo/SpringAll

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目可以使用AOP(面向切面编程)来统一处理Web请求日志。通过AOP,我们可以在请求处理的前后添加额外的逻辑,例如记录请求的时间、URL、参数等信息。 首先,我们需要在Spring Boot项目中引入spring-boot-starter-aop依赖。这可以通过在pom.xml文件中添加以下代码来实现: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 接下来,我们可以创建一个切面类,用于定义我们需要在请求处理前后执行的逻辑。我们可以使用@Aspect注解来标识该类为切面类,并使用@Before和@After注解来定义在请求处理前后执行的方法。例如,我们可以创建一个名为WebLogAspect的切面类: ```java @Aspect @Component public class WebLogAspect { @Before("execution(public * com.example.controller.*.*(..))") public void doBefore(JoinPoint joinPoint) { // 在请求处理前执行的逻辑 // 记录请求的时间、URL、参数等信息 } @After("execution(public * com.example.controller.*.*(..))") public void doAfter(JoinPoint joinPoint) { // 在请求处理后执行的逻辑 // 记录请求的处理结果等信息 } } ``` 在上述代码中,我们使用@Before注解定义了一个doBefore方法,在执行com.example.controller包下的所有公共方法之前执行。我们可以在该方法中记录请求的相关信息。类似地,我们可以使用@After注解定义一个doAfter方法,在执行请求之后执行相应的逻辑。 最后,我们需要在Spring Boot应用程序的主类上添加@EnableAspectJAutoProxy注解,以启用AOP功能。例如: ```java @SpringBootApplication @EnableAspectJAutoProxy public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 通过以上步骤,我们就可以在Spring Boot项目中使用AOP来统一处理Web请求日志了。在切面类中定义的方法将会在请求处理的前后执行,我们可以在这些方法中添加额外的逻辑来满足项目的需求。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [详解Spring Boot使用AOP统一处理Web请求日志](https://download.csdn.net/download/weixin_38595356/12780425)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Spring Boot如何使用AOP实例解析](https://download.csdn.net/download/weixin_38683562/12726375)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值