AOP日志
AOP日志就是简单记录一些用户执行的过程
- 导入依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
- 自定义注解LogAnno
//声明执行时间,runtime运行时
@Retention(RetentionPolicy.RUNTIME)
//声明作用域,method作用在方法上
@Target(ElementType.METHOD)
public @interface LogAnno {
//自定义的两个变量
String operationType();
String operationName();
}
- 接下来就是切面表达式,通知
@Aspect
@Component
public class LogUtils {
/**
* 切入点表达式 *代表一个目录 ..代表两个或多个
*/
@Pointcut("execution(* com.qianfeng..controller..*(..))")
public void pointcut() {
}
/**
* 后置通知
* @param joinPoint
* @param o
* @throws ClassNotFoundException
*/
@AfterReturning(pointcut = "pointcut()", returning = "o")
public void after(JoinPoint joinPoint, Object o) throws ClassNotFoundException {
//获取类的全名称
String classname = joinPoint.getTarget().getClass().getName();
//获取方法上的注解
Class<?> aClass = Class.forName(classname);
//获取类中的方法
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method method : declaredMethods) {
//得到方法上的LogAnno注解
LogAnno logAnno = method.getAnnotation(LogAnno.class);
if (logAnno != null) {
String operationName = logAnno.operationName();
String operationType = logAnno.operationType();
//获得用户
User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
System.out.println(operationName + "----" + operationType + "被执行了,执行者" + user.getUser_name());
}
}
}
/**
* 异常通知
* @param joinPoint
* @param t
* @throws ClassNotFoundException
*/
@AfterThrowing(pointcut = "pointcut()", throwing = "t")
public void throwing(JoinPoint joinPoint,Throwable t) throws ClassNotFoundException {
//获取类的全名称
String classname = joinPoint.getTarget().getClass().getName();
//获取方法上的注解
Class<?> aClass = Class.forName(classname);
//获取类中的方法
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method method : declaredMethods) {
//得到方法上的LogAnno注解
LogAnno logAnno = method.getAnnotation(LogAnno.class);
if (logAnno != null) {
String operationName = logAnno.operationName();
String operationType = logAnno.operationType();
//获得用户
User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
System.out.println(operationName + "----" + operationType + (user==null?"":"被执行了,执行者" + user.getUser_name())+"出现异常了");
}
}
}
}
这样就可以了!