Springboot整合AOP和注解,实现丰富的切面功能
简介
我们在文章《Spring AOP与AspectJ的对比及应用》介绍了AOP的使用,这篇文章讲解一下AOP与注解的整合,通过注解来使用AOP,会非常方便。为了简便,我们还是来实现一个计时的功能。
整合过程
首先创建一个注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PkslowLogTime {
}
然后在一个Service中使用注解:
@Service
@Slf4j
public class TestService {
@PkslowLogTime
public void fetchData() {
log.info("fetchData");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
这个Service的方法会在Controller中调用:
@GetMapping("/hello")
public String hello() {
log.info("------hello() start---");
test();
staticTest();
testService.fetchData();
log.info("------hello() end---");
return "Hello, pkslow.";
}
接着是关键一步,我们要实现切面,来找到注解并实现对应功能:
@Aspect
@Component
@Slf4j
public class PkslowLogTimeAspect {
@Around("@annotation(com.pkslow.springboot.aop.PkslowLogTime) && execution(* *(..))")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("------PkslowLogTime doAround start------");
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
// Get intercepted method details
String className = methodSignature.getDeclaringType().getSimpleName();
String methodName = methodSignature.getName();
// Measure method execution time
StopWatch stopWatch = new StopWatch(className + "->" + methodName);
stopWatch.start(methodName);
Object result = joinPoint.proceed();
stopWatch.stop();
// Log method execution time
log.info(stopWatch.prettyPrint());
log.info("------PkslowLogTime doAround end------");
return result;
}
}
@Around("@annotation(com.pkslow.springboot.aop.PkslowLogTime) && execution(* *(..))")这个表达式很关键,如果不对,将无法正确识别;还有可能出现多次调用的情况。多次调用的情况可以参考:Stackoverflow
这里使用了Spring的StopWatch来计时。
测试
通过maven build包:
$ mvn clean package
日志可以看到有对应的织入信息:
[INFO] Join point 'method-execution(java.lang.String com.pkslow.springboot.controller.TestController.hello())' in Type 'com.pkslow.springboot.controller.TestController' (TestController.java:22) advised by around advice from 'com.pkslow.springboot.aop.ControllerAspect' (ControllerAspect.class(from ControllerAspect.java))
[INFO] Join point 'method-execution(java.lang.String com.pkslow.springboot.controller.TestController.hello())' in Type 'com.pkslow.springboot.controller.TestController' (TestController.java:22) advised by before advice from 'com.pkslow.springboot.aop.ControllerAspect' (ControllerAspect.class(from ControllerAspect.java))
[INFO] Join point 'method-execution(void com.pkslow.springboot.controller.TestController.test())' in Type 'com.pkslow.springboot.controller.TestController' (TestController.java:31) advised by around advice from 'com.pkslow.springboot.aop.ControllerAspect' (ControllerAspect.class(from ControllerAspect.java))
[INFO] Join point 'method-execution(void com.pkslow.springboot.controller.TestController.test())' in Type 'com.pkslow.springboot.controller.TestController' (TestController.java:31) advised by before advice from 'com.pkslow.springboot.aop.ControllerAspect' (ControllerAspect.class(from ControllerAspect.java))
[INFO] Join point 'method-execution(void com.pkslow.springboot.controller.TestController.staticTest())' in Type 'com.pkslow.springboot.controller.TestController' (TestController.java:37) advised by around advice from 'com.pkslow.springboot.aop.ControllerAspect' (ControllerAspect.class(from ControllerAspect.java))
[INFO] Join point 'method-execution(void com.pkslow.springboot.controller.TestController.staticTest())' in Type 'com.pkslow.springboot.controller.TestController' (TestController.java:37) advised by before advice from 'com.pkslow.springboot.aop.ControllerAspect' (ControllerAspect.class(from ControllerAspect.java))
[INFO] Join point 'method-execution(void com.pkslow.springboot.service.TestService.fetchData())' in Type 'com.pkslow.springboot.service.TestService' (TestService.java:12) advised by around advice from 'com.pkslow.springboot.aop.PkslowLogTimeAspect' (PkslowLogTimeAspect.class(from PkslowLogTimeAspect.java))
启动应用后访问接口,日志如下:

总结
通过注解可以实现很多功能,也非常方便。而且注解还可以添加参数,组合使用更完美了。
代码请看GitHub: https://github.com/LarryDpk/pkslow-samples
Springboot整合AOP和注解,实现丰富的切面功能的更多相关文章
- SpringBoot整合定时任务----Scheduled注解实现(一个注解全解决)
一.使用场景 定时任务在开发中还是比较常见的,比如:定时发送邮件,定时发送信息,定时更新资源,定时更新数据等等... 二.准备工作 在Spring Boot程序中不需要引入其他Maven依赖 (因为s ...
- spring框架aop用注解形式注入Aspect切面无效的问题解决
由于到最后我的项目还是有个邪门的错没解决,所以先把文章大概内容告知: 1.spring框架aop注解扫描默认是关闭的,得手动开启. 2.关于Con't call commit when autocom ...
- 【使用篇二】SpringBoot整合aop(13)
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是Spring框架中的一个重要内容,它通 ...
- springboot整合aop实现网站访问日志记录
目的: 统一日志输出格式,统计访问网站的ip. 思路: 1.针对不同的调用场景定义不同的注解,目前想的是接口层和服务层. 2.我设想的接口层和服务层的区别在于: (1)接口层可以打印客户端IP,而服务 ...
- SpringBoot整合Mybatis使用注解或XML的方式开发
2018-6-4 补充mybatis-spring-boot注解的使用 1.导包 只需要再导入mysql+mybatis两个包 <dependency> <groupId>or ...
- SpringBoot整合AOP
一.创建LogComponent类 类上加上@Component和@Aspect 表示把该类注册成spring组件和aop 二.创建6个方法 2.1 @Poin ...
- springboot整合mybatis之注解方式
1. 创建maven项目,工程目录如下图 2. 在pom.xml文件中添加mybatis依赖. 3. 创建实体类,并生成construct方法,getter和setter方法.同时在数据库中创建对应的 ...
- SpringBoot整合quartz实现动态启动,停止定时任务功能
注意:这个方法当程序重启之后会失效,所以必须将定时任务持久化到数据库,然后程序启动的时候重新把数据库的定时任务加载到quartz中 springboot程序启动初始化代码参考:https://www. ...
- Spring AOP通过注解的方式设置切面和切入点
切面相当于一个功能的某一个类,切入点是这个类的某部分和需要额外执行的其他代码块,这两者是多对多的关系,在代码块处指定执行的条件. Aspect1.java package com.yh.aop.sch ...
- Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用
==============Springboot的日志管理============= springboot无需引入日志的包,springboot默认已经依赖了slf4j.logback.log4j等日 ...
随机推荐
- HMM算法python实现
基础介绍,后5项为基础5元素 Q = ['q0', 'q1', 'q2', 'q3'] # 状态集合 States,共 N 种状态 V = ['v0', 'v1'] # 观测集合 Observatio ...
- 2022春每日一题:Day 39
题目:[USACO1.4]等差数列 Arithmetic Progressions 一个很显然的做法,枚举公差,首项,p,q这样的话复杂度爆炸,不过可以肯定的一点,如果我们这样做,找到了答案就可以直接 ...
- 2022春每日一题:Day 22
题目:[HAOI2008]糖果传递 光看题几乎没有思路,但是显然到最后每个人手中一定有 d=s/n个糖果(s为所有人糖果总和),不妨设2号给1号x2个糖果,3号给2号x3个.....1号给n号x1个, ...
- mindxdl--common--web_cert_utils.go
// Copyright (c) 2021. Huawei Technologies Co., Ltd. All rights reserved.// Package common this file ...
- 1.3 Apache Hadoop的重要组成-hadoop-最全最完整的保姆级的java大数据学习资料
目录 1.3 Apache Hadoop的重要组成 1.3 Apache Hadoop的重要组成 Hadoop=HDFS(分布式文件系统)+MapReduce(分布式计算框架)+Yarn(资源协调框架 ...
- MAUI Blazor (Windows) App 动态设置窗口标题
接着上一篇"如何为面向 Windows 的 MAUI Blazor 应用程序设置窗口标题?" Tips: 总所周知,MAUI 除了 Windows App 其他平台窗口是没有 Ti ...
- 记录一次缓存引起的线上BUG
背景 有一个需求大概是这样的,为了提高推荐系统的性能,需要本来从A服务获取的帖子信息,改为从Redis里面重新读取 Redis里面没有存帖子的所有信息,只存储了推荐系统必要的字段 大概是这样的: 至于 ...
- 1分钟理清楚C++类模板和模板类区别
1.定义区别 类模板和模板类主要关注点是后一个单词. 类模板:主要描述的是模板,这个模板是类的模板.可以理解为一个通用的类,这个类中的数据成员,成员函数的形参类型以及成员函数的返回值类型不用具体的指定 ...
- 事件 jQuery类库、Bootstrap页面框架
目录 jQuery查找标签 基本选择器 组合选择器 层级选择器 属性选择器 基本筛选器 表单筛选器 筛选器方法 链式的本质(jQuery一行代码走天下) 操作标签 class操作 位置操作 文本操作 ...
- java中的动态绑定机制
本文主要讲述java中的动态绑定机制. 老韩ppt关于动态绑定机制: 示例代码如下: public class DynamicBinding { public static void main(Str ...