Spring AOP之Controller層AOP實現日志功能


前言

在項目中我們需要知道那個用戶那個ip請求了那個接口,我們需要將日志寫入數據庫,來監控哪些功能在哪個時間段被哪些模塊調用。這里使用的是spring AOP結合注解對Controller進行切面。

一、導入jar

對於基礎包這里沒有列出
    <!--aop所依賴的包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>

二、編寫注解類


/**
 *自定義注解 攔截Controller
 */
@Target({ElementType.PARAMETER, ElementType.METHOD}) //作用范圍為方法和參數
@Retention(RetentionPolicy.RUNTIME) //指定生命周期為內存可讀
@Documented //指定其為注解
public @interface SystemControllerLog {
    /**
     * 操作說明
     */
    public String description() default "";

}

三、編寫切面類


/**
 * 切點類
 * @author tiangai
 * @since 2014-08-05 Pm 20:35
 * @version 1.0
 */
@Aspect
public  class SystemLogAspect {

    //注入Service用於把日志保存數據庫
    @Resource
    private LogService logService;
    //本地異常日志記錄對象
    private  static  final Logger logger = Logger.getLogger(SystemLogAspect.class);


    //Controller層切點
    @Pointcut("@annotation(com.hsy.aspect.SystemControllerLog)")
    public  void controllerAspect() {}


    @AfterReturning(pointcut="controllerAspect()",returning="obj")
    public void myAfterReturning(JoinPoint joinPoint,Object obj) {
        logger.info("我是Controller層的返回通知");
        logger.info("拿到返回的數據---->"+obj);
        logger.info("拿到Controller注解描述"+ getControllerMethodDescription(joinPoint));
    }

    /**
     * 獲取注解中對方法的描述信息 用於Controller層注解
     *
     * @param joinPoint 切點
     * @return 方法描述
     * @throws Exception
     */
    public  static String getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemControllerLog. class).description();
                    break;
                }
            }
        }
        return description;
    }

}

四、配置springmvc.xml

這里有一個坑一定要是springmvc不能是spring
    <!--通知spring使用cglib而不是jdk的來生成代理方法 AOP可以攔截到Controller -->
	<aop:aspectj-autoproxy proxy-target-class="true" />

	<!-- 使用了@AspectJ注解的切面類 -->
	<bean class="com.hsy.aspect.SystemLogAspect"/>

五、在Controller層加入自定義注解

@RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    //此處為記錄AOP攔截Controller記錄用戶操作
    @SystemControllerLog(description = "登錄賬號")
    public String selectUser(@RequestBody(required=true) Map<String,String> map  ) throws Exception {
    
    return "test";
 }

六、測試

在Postman中進行測試

成功


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM