spring 自定义注解(aop实现)
使用示例
自定义注解标注在service层的方法上,统计标注了注解的方法执行时间
CustomAnnotation
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
}
HelloService
public interface HelloService {
String hello();
String hello2();
}
HelloServiceImpl
@Service
public class HelloServiceImpl implements HelloService {
@Override
@CustomAnnotation
public String hello() {
return "hello";
}
@Override
public String hello2(){
return "hello2";
}
}
CustomAspect
@Aspect
@Component
public class CustomAspect {
@Pointcut("@annotation(com.example.demo.annotation.CustomAnnotation)")
public void fun(){
}
@Around("fun()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
Object result = null;
long startTime = System.currentTimeMillis();
try {
result = joinPoint.proceed();
}catch (Throwable e){
e.fillInStackTrace();
throw e;
}
finally {
long spendTime = (System.currentTimeMillis() - startTime);
System.out.println(method.getDeclaringClass().getName()+"."+method.getName()+"执行耗时:"+spendTime+"ms");
}
return result;
}
}
HelloController
@RestController
public class HelloController {
@Resource
private HelloService helloService;
@RequestMapping("/hello")
public String hello(){
return helloService.hello();
}
@RequestMapping("/hello2")
public String hello2(){
return helloService.hello2();
}
}
使用测试
localhost:8080/hello,控制台输出:
2022-04-25 14:13:13.054 INFO 2139 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 880 ms
2022-04-25 14:13:13.386 INFO 2139 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-04-25 14:13:13.398 INFO 2139 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.557 seconds (JVM running for 2.005)
2022-04-25 14:13:15.410 INFO 2139 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-25 14:13:15.411 INFO 2139 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-25 14:13:15.412 INFO 2139 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
com.example.demo.service.impl.HelloServiceImpl.hello执行耗时:9ms
localhost:8080/hello,控制台无输出
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)