aop+自定義注解


自定義注解,並且實現,需要兩個文件;

 

自定義注解類:

package com.clc.server.annotation;

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

@Target(value = {ElementType.TYPE, ElementType.METHOD})//使用位置(類,方法)
@Retention(RetentionPolicy.RUNTIME)//加載到jvm里運行
public @interface Clc {
    String value(); //注解的屬性,如果只有一個屬性,一般叫value
    String name() default ""; //屬性,默認值"",可以不寫
}

定義好注解后,需要解析類來實現,此處使用aop來實現;

package com.clc.server.aop;

import com.clc.server.annotation.Clc;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 解析clc注解使用
 */
@Aspect//來定義一個切面
@Component
public class ClcAop {

    //定義切入點
    @Pointcut("@annotation(com.clc.server.annotation.Clc)")
    public void auditAspect() {
        System.out.println("1221212132");
    }

    //通知
    @Before("auditAspect()")
    public void doBefore(JoinPoint joinPoint) {
        System.out.println("觸發到 @Before(\"auditAspect()\")");
    }

    /**
     * 后置通知
     *
     * @param joinPoint 切點
     */
    @AfterReturning("auditAspect()")
    public void doAfrterReturning(JoinPoint joinPoint) {

        Object[] args = joinPoint.getArgs();
        System.out.println("觸發 @AfterReturning(\"auditAspect()\")");
        System.out.println(args.length);
        getControllerMethodDescription(joinPoint);
    }

    /**
     * 獲取注解中對方法的描述信息
     *
     * @param joinPoint 切點
     * @return 方法描述
     */
    public static void getControllerMethodDescription(JoinPoint joinPoint) {
        String targetName = joinPoint.getTarget().getClass().getName();    //獲得執行方法的類名
        String methodName = joinPoint.getSignature().getName();            //獲得執行方法的方法名
        Object[] arguments = joinPoint.getArgs();                          //獲取切點方法的所有參數類型
        try {
            Class targetClass = Class.forName(targetName);

            Method[] methods = targetClass.getMethods();    //獲取公共方法,不包括類私有的
            String value = "";
            String name = "";
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] clazzs = method.getParameterTypes();     //對比方法中參數的個數
                    if (clazzs.length == arguments.length) {
                        value = method.getAnnotation(Clc.class).value();
                        name = method.getAnnotation(Clc.class).name();
                        break;
                    }
                }
            }
            System.out.println("value=" + value);
            System.out.println("name=" + name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

測試注解,使用

   /**
     * 測試自定義注解
     */
    @Clc(value = "clc", name = "name")
    @RequestMapping(value = "/add2", method = RequestMethod.GET)
    public String add2() {
        //獲取本服務的信息
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = 2;
        String info = "/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + "結果:" + r;
        logger.info(info);
        return info;
    }

觸發注解后:

2018-09-13 20:11:07.487  INFO 14012 --- [nio-9003-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-09-13 20:11:07.487  INFO 14012 --- [nio-9003-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-09-13 20:11:07.514  INFO 14012 --- [nio-9003-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 27 ms
觸發到 @Before("auditAspect()")
2018-09-13 20:11:07.554  INFO 14012 --- [nio-9003-exec-1] c.c.s.c.ComputeController@7fcff1b9       : /add, host:localhost, service_id:clc-service結果:2
觸發 @AfterReturning("auditAspect()")
0
value=clc
name=name
2018-09-13 20:15:44.844  INFO 14012 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration

簡單的自定義注解,已經實現

 


免責聲明!

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



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