1. 程式人生 > 實用技巧 >spring 自定義註解

spring 自定義註解

java在jdk1.5中引入了註解,spring框架也正好把java註解發揮得淋漓盡致。

下面會講解Spring中自定義註解的簡單流程,其中會涉及到spring框架中的AOP(面向切面程式設計)相關概念。
不清楚java註解的,可以先了解java自定義註解:Java自定義註解

一、建立自定義註解

requestUrl 為我們自定義的一個引數

package com.sam.annotation;

import java.lang.annotation.*;

/**
 * @author sam
 * @since 2017/7/13
 */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyLog {

    String requestUrl();

}

二、解析註解

此處使用了spring的AOP(面向切面程式設計)特性

通過@Aspect註解使該類成為切面類
通過@Pointcut 指定切入點 ,這裡指定的切入點為MyLog註解型別,也就是被@MyLog註解修飾的方法,進入該切入點。
  • @Before 前置通知:在某連線點之前執行的通知,但這個通知不能阻止連線點之前的執行流程(除非它丟擲一個異常)。
  • @Around環繞通知:可以實現方法執行前後操作,需要在方法內執行point.proceed(); 並返回結果。
  • @AfterReturning 後置通知:在某連線點正常完成後執行的通知:例如,一個方法沒有丟擲任何異常,正常返回。
  • @AfterThrowing 異常通知:在方法丟擲異常退出時執行的通知。
  • @After 後置通知:在某連線點正常完成後執行的通知:例如,一個方法沒有丟擲任何異常,正常返回。
package com.sam.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author sam
 * @since 2017/7/13
 */
@Aspect //AOP 切面
@Component
public class MyLogAspect {


    //切入點
    @Pointcut(value = "@annotation(com.sam.annotation.MyLog)")
    private void pointcut() {

    }


    /**
     * 在方法執行前後
     *
     * @param point
     * @param myLog
     * @return
     */
    @Around(value = "pointcut() && @annotation(myLog)")
    public Object around(ProceedingJoinPoint point, MyLog myLog) {

        System.out.println("++++執行了around方法++++");

        String requestUrl = myLog.requestUrl();

        //攔截的類名
        Class clazz = point.getTarget().getClass();
        //攔截的方法
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        System.out.println("執行了 類:" + clazz + " 方法:" + method + " 自定義請求地址:" + requestUrl);

        try {
            return point.proceed(); //執行程式
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return throwable.getMessage();
        }
    }

    /**
     * 方法執行後
     *
     * @param joinPoint
     * @param myLog
     * @param result
     * @return
     */
    @AfterReturning(value = "pointcut() && @annotation(myLog)", returning = "result")
    public Object afterReturning(JoinPoint joinPoint, MyLog myLog, Object result) {

//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpSession session = request.getSession();

        System.out.println("++++執行了afterReturning方法++++");

        System.out.println("執行結果:" + result);

        return result;
    }

    /**
     * 方法執行後 並丟擲異常
     *
     * @param joinPoint
     * @param myLog
     * @param ex
     */
    @AfterThrowing(value = "pointcut() && @annotation(myLog)", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, MyLog myLog, Exception ex) {
        System.out.println("++++執行了afterThrowing方法++++");
        System.out.println("請求:" + myLog.requestUrl() + " 出現異常");
    }

}

三、使用自定義註解

在controller中直接使用註解@MyLog

package com.sam.controller;

import com.sam.annotation.MyLog;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sam
 * @since 2017/7/13
 */
@RestController
@RequestMapping(value = "/index")
public class IndexController {

    @MyLog(requestUrl = "/index請求")
    @RequestMapping(method = RequestMethod.GET)
    public String index() {
        return "index";
    }
}

啟動專案,訪問http://localhost:8080/index

結果

++++執行了around方法++++
執行了 類:class com.yfs.controller.IndexController 方法:public java.lang.String com.yfs.controller.IndexController.index() 自定義請求地址:/index請求
++++執行了afterReturning方法++++
執行結果:index

java在jdk1.5中引入了註解,spring框架也正好把java註解發揮得淋漓盡致。

下面會講解Spring中自定義註解的簡單流程,其中會涉及到spring框架中的AOP(面向切面程式設計)相關概念。
不清楚java註解的,可以先了解java自定義註解:Java自定義註解

一、建立自定義註解

requestUrl 為我們自定義的一個引數

package com.sam.annotation;

import java.lang.annotation.*;

/**
 * @author sam
 * @since 2017/7/13
 */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyLog {

    String requestUrl();

}

二、解析註解

此處使用了spring的AOP(面向切面程式設計)特性

通過@Aspect註解使該類成為切面類
通過@Pointcut 指定切入點 ,這裡指定的切入點為MyLog註解型別,也就是被@MyLog註解修飾的方法,進入該切入點。
  • @Before 前置通知:在某連線點之前執行的通知,但這個通知不能阻止連線點之前的執行流程(除非它丟擲一個異常)。
  • @Around環繞通知:可以實現方法執行前後操作,需要在方法內執行point.proceed(); 並返回結果。
  • @AfterReturning 後置通知:在某連線點正常完成後執行的通知:例如,一個方法沒有丟擲任何異常,正常返回。
  • @AfterThrowing 異常通知:在方法丟擲異常退出時執行的通知。
  • @After 後置通知:在某連線點正常完成後執行的通知:例如,一個方法沒有丟擲任何異常,正常返回。
package com.sam.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author sam
 * @since 2017/7/13
 */
@Aspect //AOP 切面
@Component
public class MyLogAspect {


    //切入點
    @Pointcut(value = "@annotation(com.sam.annotation.MyLog)")
    private void pointcut() {

    }


    /**
     * 在方法執行前後
     *
     * @param point
     * @param myLog
     * @return
     */
    @Around(value = "pointcut() && @annotation(myLog)")
    public Object around(ProceedingJoinPoint point, MyLog myLog) {

        System.out.println("++++執行了around方法++++");

        String requestUrl = myLog.requestUrl();

        //攔截的類名
        Class clazz = point.getTarget().getClass();
        //攔截的方法
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        System.out.println("執行了 類:" + clazz + " 方法:" + method + " 自定義請求地址:" + requestUrl);

        try {
            return point.proceed(); //執行程式
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return throwable.getMessage();
        }
    }

    /**
     * 方法執行後
     *
     * @param joinPoint
     * @param myLog
     * @param result
     * @return
     */
    @AfterReturning(value = "pointcut() && @annotation(myLog)", returning = "result")
    public Object afterReturning(JoinPoint joinPoint, MyLog myLog, Object result) {

//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpSession session = request.getSession();

        System.out.println("++++執行了afterReturning方法++++");

        System.out.println("執行結果:" + result);

        return result;
    }

    /**
     * 方法執行後 並丟擲異常
     *
     * @param joinPoint
     * @param myLog
     * @param ex
     */
    @AfterThrowing(value = "pointcut() && @annotation(myLog)", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, MyLog myLog, Exception ex) {
        System.out.println("++++執行了afterThrowing方法++++");
        System.out.println("請求:" + myLog.requestUrl() + " 出現異常");
    }

}

三、使用自定義註解

在controller中直接使用註解@MyLog

package com.sam.controller;

import com.sam.annotation.MyLog;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sam
 * @since 2017/7/13
 */
@RestController
@RequestMapping(value = "/index")
public class IndexController {

    @MyLog(requestUrl = "/index請求")
    @RequestMapping(method = RequestMethod.GET)
    public String index() {
        return "index";
    }
}

啟動專案,訪問http://localhost:8080/index

結果

++++執行了around方法++++
執行了 類:class com.yfs.controller.IndexController 方法:public java.lang.String com.yfs.controller.IndexController.index() 自定義請求地址:/index請求
++++執行了afterReturning方法++++
執行結果:index

以上講解了Spring實現自定義註解的簡單流程,需要做更多的自定義操作,則需要在切面類裡面進行程式設計了。


本文出自:https://my.oschina.net/magicalSam/blog/1359369