@Aspect註解方式-AOP加強

使用@aspject進行aop加強處理,示例是相似於一個日誌記錄功能。java

1.demo-web新增

  • Log
package com.company.aspectj;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 註解生命週期-運行時
 * 註解目標:方法
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
    String value() default "";
}
  • LogAspejctj
package com.company.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class LogAspectj {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspectj.class);

    @AfterReturning(value = "@annotation(com.company.aspectj.Log)",returning = "ret")
    public void LogAfterReturning(JoinPoint joinPoint,Object ret){
        Object[] args = joinPoint.getArgs();
        LOGGER.info("方法入參:{}",args);
        LOGGER.info("返回值:{}",ret);
    }
}

 

2.配置

<!--@aspectj啓動,子類代理-->
<aop:aspectj-autoproxy proxy-target-class="true"/>

<!--將定義aspectj掃入spring bean容器裏(二選一)-->
<context:component-scan base-package="com.company.aspectj">
    <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<!--<bean id="logAspectj" class="com.company.aspectj.LogAspectj"/>-->

 

3.實例測試

  • 將Log註解值UserController中qryUserById方法上
@RequestMapping("qryUserById")
@ResponseBody
@Log
public User qryUserById(Long id) throws DemoException{
    if(id == null){
        throw new DemoException("id爲空");
    }

    return userService.qryUserById(id);
}
  • 地址欄=>http://localhost:8080/demo-web/user/qryUserById.do?id=1,console輸出

相關文章
相關標籤/搜索