代碼筆記

「Java筆記」 在Spring Boot中用註解快捷的使用AOP

 

讓我們來面向切面編程吧,我們可以用AOP將某個共用的方法抽離出來,並在IOC容器中統一管理,而在Spring中是無法省略配置的,在Spring Boot中則完全不用,非常方便。下面以”記錄接口的訪問時長”功能場景來看看如何在 springboot 中使用 AOP。

添加 spring-boot 的 aop 依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

編寫切面類和切面邏輯

@Aspect
@Component
public class HttpRequestAspect {

    private static final Logger log = LoggerFactory.getLogger(HttpRequestAspect.class);

    public static long startTime;
    public static long endTime;

    /*@PointCut註解表示表示橫切點,哪些方法需要被橫切*/
    /*切點表達式*/
    @Pointcut("execution(public * com.simons.cn.springbootdemo.controller.*.*(..))")
    /*切點簽名*/
    public void print() {

    }

    /*@Before註解表示在具體的方法之前執行*/
    @Before("print()")
    public void before(JoinPoint joinPoint) {
        log.info("前置切面before……");
        startTime = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestURI = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();   //這個方法取客戶端ip"不夠好"
        String requestMethod = request.getMethod();
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        log.info("請求url=" + requestURI + ",客戶端ip=" + remoteAddr + ",請求方式=" + requestMethod + ",請求的類名=" + declaringTypeName + ",方法名=" + methodName + ",入參=" + args);
    }

    /*@After註解表示在方法執行之後執行*/
    @After("print()")
    public void after() {
        endTime = System.currentTimeMillis() - startTime;
        log.info("後置切面after……");
    }

    /*@AfterReturning註解用於獲取方法的返回值*/
    @AfterReturning(pointcut = "print()", returning = "object")
    public void getAfterReturn(Object object) {
        log.info("本次接口耗時={}ms", endTime);
        log.info("afterReturning={}", object.toString());
    }
}

1.可以看到我把@PointCut(×××)給單獨拎出來了,省的在@Before、@After、@AfterReturn 註解中重複寫,而是直接用類似於@Before(value=”print()”)代替,減少重複性代碼;

2.execution(public com.simons.cn.springbootdemo.controller..*(..)) 表示 com.simons.cn.springbootdemo.controller 包下的所有類中的所有方法,”..”表示所有方法中的參數不限個數;

編寫測試類測試下

@GetMapping(value = "/index")
@ResponseBody
public String index() {
    ActivitySystemVariable systemVariable = activitySystemVariableMapper.selectByPrimaryKey(258);
    return systemVariable.toString();
}

日誌輸出結果,ok

2018-06-28 11:21:10.939  INFO 10696 --- [nio-8888-exec-8] c.s.cn.springbootdemo.HttpRequestAspect  : 前置切面before……
2018-06-28 11:21:10.939  INFO 10696 --- [nio-8888-exec-8] c.s.cn.springbootdemo.HttpRequestAspect  : 請求url=/index,客戶端ip=0:0:0:0:0:0:0:1,請求方式=GET,請求的類名=com.simons.cn.springbootdemo.controller.IndexController,方法名=index,入參=[Ljava.lang.Object;@1efabee
2018-06-28 11:21:10.951  INFO 10696 --- [nio-8888-exec-8] c.s.cn.springbootdemo.HttpRequestAspect  : 後置切面after……
2018-06-28 11:21:10.951  INFO 10696 --- [nio-8888-exec-8] c.s.cn.springbootdemo.HttpRequestAspect  : 本次接口耗時=12ms
2018-06-28 11:21:10.951  INFO 10696 --- [nio-8888-exec-8] c.s.cn.springbootdemo.HttpRequestAspect  : afterReturning=ActivitySystemVariable{id=258, name='simonsfan測試', svKey='simons-key', value='simons-value', memo='simonsfan測試', typeCode='', cataLog=0, createTime=2018-06-28 11:18:19.0}

View Comments

Recent Posts

Flexible Shipping Pro

在WordPress的世界裡,…

3天 ago

2023 年 WordPress 中最棒的多語言翻譯外掛推薦

擔心如何翻譯您的網站語言以支持…

1年 ago

2023 年 WordPress 中最棒的可視化頁面構建器外掛推薦

在設計任何頁面或網站時,對於不…

1年 ago

Ella 多用途 Shopify 佈景主題

Shopify 佈景主題市場上有許…

1年 ago

AI Engine Pro

喵容今天帶來的 AI Engi…

1年 ago

AIKit

喵容今天為您帶來 AIKit …

1年 ago