0.前言
开发中经常会遇到处理重复的逻辑,如果每次都要去重复实现,则开发效率很低,因此可以去同一处理,比较常用的方式有拦截器,过滤器,aop等等,这里介绍通过自定义注解来处理,这样的优点是可以很好的控制粒度,示例为通过自定义注解统计请求的耗时.
1.maven依赖
1 <dependency>
2 <groupId>org.springframework.boot
</groupId>
3 <artifactId>spring-boot-starter-aop
</artifactId>
4 <version>1.5.9.RELEASE
</version>
5 </dependency>
2.自定义注解
1 import java.lang.annotation.ElementType;
2 import java.lang.annotation.Retention;
3 import java.lang.annotation.RetentionPolicy;
4 import java.lang.annotation.Target;
5
6 @Target(ElementType.METHOD)
7 @Retention(RetentionPolicy.RUNTIME)
8 public @
interface MyAnnotation {
9 String note()
default ""
;
10 }
3.AOP
1 import org.aspectj.lang.JoinPoint;
2 import org.aspectj.lang.annotation.After;
3 import org.aspectj.lang.annotation.Aspect;
4 import org.aspectj.lang.annotation.Before;
5 import org.aspectj.lang.annotation.Pointcut;
6 import org.springframework.stereotype.Component;
7
8 @Aspect
9 @Component
10 public class LogMethodCostTimeAspect {
11
12 ThreadLocal<Long> beginTime =
new ThreadLocal<>
();
13
14 @Pointcut("@annotation(myAnnotation)"
)
15 public void myPointcut(MyAnnotation myAnnotation) {
16 }
17
18 @Before("myPointcut(myAnnotation)"
)
19 public void doBefore(JoinPoint joinPoint, MyAnnotation myAnnotation) {
20 System.err.println("方法执行开始"
);
21 //记录请求到达时间
22 beginTime.set(System.currentTimeMillis());
23
24 }
25
26 @After("myPointcut(myAnnotation)"
)
27 public void doAfter(MyAnnotation myAnnotation) {
28 System.err.println(myAnnotation.note() + (System.currentTimeMillis() - beginTime.get()) + " ms"
);
29 System.err.println("方法执行结束"
);
30 }
31
32 }
4.Service实现
1 @Service("demoService"
)
2 public class DemoServiceImpl
implements DemoService{
3
4 @Override
5 @MyAnnotation(note = "执行 demo 方法耗时"
)
6 public void doSth() {
7 for (
int i = 0; i < 100; i++
) {
8 System.out.println("do something ..."
);
9 }
10 }
11 }
5.Controller
1 @Controller
2 public class HelloController {
3
4 @Autowired
5 private DemoService demoService;
6
7 @RequestMapping(value = "/hello"
)
8 @ResponseBody
9 public void getTime() {
10 demoService.doSth();
11 }
12 }
转载于:https://www.cnblogs.com/wangliangwu/p/10019844.html