天天看點

深入淺出 java 注解-05-java 注解結合 Spring AOP目錄Spring Aop + Annotation執行個體代碼位址系列導航

目錄

  • 目錄
  • Spring Aop + Annotation
  • 執行個體
    • maven jar 引入
    • 注解的定義 & 使用
    • 測試 & 結果
  • 代碼位址
  • 系列導航

Spring Aop + Annotation

Spring Aop 是一種經常被我們提及地代碼增強功能,結合注解可以使得代碼增強變得更加靈活。

執行個體

maven jar 引入

<properties>
    <spring.version>4.2.6.RELEASE</spring.version>
    <aspectj.version>1.8.5</aspectj.version>
    <junit.version>4.12</junit.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--test-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <!-- AOP -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
</dependencies>
           

注解的定義 & 使用

  • Log.java
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {

    /**
     * 輸出入參
     * @return 是否
     */
    boolean logParam() default true;

    /**
     * 輸出出參
     * @return 是否
     */
    boolean logReturn() default true;

    /**
     * 輸出時間
     * @return 是否
     */
    boolean logTime() default true;

}
           
  • UserService.java

使用注解

import com.ryo.jdk.annotation.spring.annotation.Log;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Log(logParam = true, logReturn = true, logTime = true)
    public int queryCount(String username) {
        System.out.println("call query count...");
        return ;
    }

    public void save(String username, int age) {
        System.out.println("call save...");
    }

}
           
  • LogInterceptor.java

基于 Spring 的 AOP 代碼增強

import com.ryo.jdk.annotation.spring.annotation.Log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
public class LogInterceptor {

    /**
     * 開始時間
     */
    private long beginTime;
    /**
     * 結束時間
     */
    private long endTime;

    /**
     * 攔截service 下所有的 @Log 方法
     */
    @Pointcut("execution(public * com.ryo.jdk.annotation.spring.service..*(..))")
    public void pointCut() {
        //just the point cut
    }

    /**
     * 攔截處理
     *
     * @param point point 資訊
     * @return result
     * @throws Throwable if any
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        beginTime = System.currentTimeMillis();

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        Log log = method.getAnnotation(Log.class);
        if(log == null) {
            return point.proceed();
        }

        //1. 入參
        if(log.logParam()) {
            System.out.println("[PARAM]: " + Arrays.toString(point.getArgs()));
        }
        Object result = point.proceed();
        //2. 出參
        if(log.logReturn()) {
            System.out.println("[RETURN]: " + result);
        }
        //3. 消耗時間
        if(log.logTime()) {
            endTime = System.currentTimeMillis();
            System.out.println("[COST]: " + (endTime-beginTime));
        }
        return result;
    }
}
           
  • applicationContext-aop.xml

spring 關于 aop 的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.ryo.jdk.annotation.spring"/>

    <!--啟動代理-->
    <!--aspect annotation-->
    <aop:aspectj-autoproxy/>

</beans>
           

測試 & 結果

  • UserServiceTest.java

測試代碼

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-aop.xml"})
public class UserServiceTest {


    @Autowired
    private UserService userService;

    @Test
    public void queryCountTest() {
        userService.queryCount("ryo");
    }

    @Test
    public void saveTest() {
        userService.save("ryo", );
    }

}
           
  • 測試結果

queryCountTest 測試結果

[PARAM]: [ryo]
call query count...
[RETURN]: 0
[COST]: 27
           

saveTest 測試結果

代碼位址

annotation 定義與解析

系列導航

系列導航

繼續閱讀