aop注解方式实现日志管理
程序员文章站
2022-04-25 19:38:05
...
maven需要的jar:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
springServlet-mvc.xml:
<!--proxy-target-class="true"强制使用cglib代理 , 如果为false则spring会自动选择
加上proxy-target-class="true"是为了可以拦截controller里面的方法
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
自定义注解
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**模块*/
String module() default "";
/**描述*/
String description() default "";
}
切面类
package io.zhijian.log.aop;
import io.zhijian.log.annotation.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import java.lang.reflect.Method;
/**
* 日志切面处理类
*/
@Aspect
public class LogAspect {
/**
* 日志切入点
*/
private LogPoint logPoint;
/**
* 保存系统操作日志
*
* @param joinPoint 连接点
* @return 方法执行结果
* @throws Throwable 调用出错
*/
@Around(value = "@annotation(io.zhijian.log.annotation.Log)")
public Object save(ProceedingJoinPoint joinPoint) throws Throwable {
/**
* 解析Log注解
*/
String methodName = joinPoint.getSignature().getName();
Method method = currentMethod(joinPoint, methodName);
Log log = method.getAnnotation(Log.class);
/**
* 日志入库
*/
if (log != null) {
logPoint.save(joinPoint, methodName, log.module(), log.description());
}
/**
* 方法执行
*/
return joinPoint.proceed();
}
/**
* 获取当前执行的方法
*
* @param joinPoint 连接点
* @param methodName 方法名称
* @return 方法
*/
private Method currentMethod(ProceedingJoinPoint joinPoint, String methodName) {
/**
* 获取目标类的所有方法,找到当前要执行的方法
*/
Method[] methods = joinPoint.getTarget().getClass().getMethods();
Method resultMethod = null;
for (Method method : methods) {
if (method.getName().equals(methodName)) {
resultMethod = method;
break;
}
}
return resultMethod;
}
public LogPoint getLogPoint() {
return logPoint;
}
public void setLogPoint(LogPoint logPoint) {
this.logPoint = logPoint;
}
}
controller应用日志
@RequestMapping("/xx.do")
@Log(module="模块:",description="描述")//注意:这个不加的话,这个方法的日志记录不会被插入
public ModelAndView skipPage(HttpServletRequest request,HttpServletResponse response) throws IOException{
}
可参考:http://www.cnblogs.com/jianjianyang/p/4910851.html
http://blog.csdn.net/pangliang_csdn/article/details/68946506