1. 程式人生 > >AOP日誌記錄

AOP日誌記錄

AOP日誌

AOP日誌就是簡單記錄一些使用者執行的過程
  1. 匯入依賴包
<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
  1. 自定義註解LogAnno
//宣告執行時間,runtime執行時
@Retention(RetentionPolicy.RUNTIME)
//宣告作用域,method作用在方法上
@Target(ElementType.METHOD)

public @interface LogAnno {

    //自定義的兩個變數
    String operationType();

    String operationName();
}
  1. 接下來就是切面表示式,通知

@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())+"出現異常了");
            }
        }
    }
}

這樣就可以了!