我想写一个自定义注释,比如@loggable,当在方法级别声明时,会向用户显示一些关于当前方法的日志消息。我该怎么做?这可能吗?如何用spring注册这个注释?我在哪里写日志记录逻辑?
提前致谢。
答案 0 :(得分:6)
这是一个关于如何做到这一点的好教程
Custom Annotations with Spring AOP
编辑1
嗯,这是我写的一个示例程序,可以实现你想要的。 这种日志方法,甚至是Method的执行时间。 希望这会有所帮助。
可记录 - 自定义注释声明
package com.test.common.custom.annotation;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Loggable {
String message() default "Audit Message";
}
LogManager - 这告诉AspectJ有哪些拦截方法。
package com.test.common.custom.annotation.pointcutmgr;
@Service
@Aspect
public class LogManager {
@Pointcut("execution(* com.test.service.*.*(..))")
public void auditLog() {}
@Pointcut("execution(* com.test.service.*.*(..))")
public void performanceLog(){
}
}
LogInterceptor - 建议如何处理截获的方法
package com.test.common.custom.annotation;
@Service
@Aspect
public class LogInterceptor {
@Before(value = "com.test.common.custom.annotation.pointcutmgr.LogManager.auditLog()"
+ "&& target(bean) "
+ "&& @annotation(com.test.common.custom.annotation.Loggable)"
+ "&& @annotation(logme)", argNames = "bean,logme")
public void log(JoinPoint jp, Object bean, Loggable logme) {
System.out.println(String.format("Log Message: %s", logme.message()));
System.out.println(String.format("Bean Called: %s", bean.getClass()
.getName()));
System.out.println(String.format("Method Called: %s", jp.getSignature()
.getName()));
}
@Around(value = "com.test.common.custom.annotation.pointcutmgr.LogManager.auditLog()"
+ "&& target(bean) "
+ "&& @annotation(com.test.common.custom.annotation.Loggable)"
+ "&& @annotation(logme)", argNames = "bean,logme")
public void performanceLog(ProceedingJoinPoint joinPoint, Object bean, Loggable logme) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
joinPoint.proceed();
stopWatch.stop();
StringBuffer logMessage = new StringBuffer();
logMessage.append(joinPoint.getTarget().getClass().getName());
logMessage.append(".");
logMessage.append(joinPoint.getSignature().getName());
logMessage.append("(");
// append args
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
logMessage.append(args[i]).append(",");
}
if (args.length > 0) {
logMessage.deleteCharAt(logMessage.length() - 1);
}
logMessage.append(")");
logMessage.append(" execution time: ");
logMessage.append(stopWatch.getTotalTimeMillis());
logMessage.append(" ms");
System.out.println(logMessage.toString());
}
}
继承人如何使用
使用@Loggable
,will print logs and performance statistics
@Loggable(message = "Add Cutomer is fired")
public void addCustomer(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("addCustomer() is running ");
}