AOP自定义注解

引用:https://www.cnblogs.com/huangting/p/11808634.html

目的:

1.Java注解简介

2.Java元注解(重点)

3.自定义注解

      案例一(获取类与方法上的注解值)

案例二(获取类属性上的注解属性值)

案例三(获取参数修饰注解对应的属性值)

4.Aop自定义注解的应用(重点)



Java注解简介

1. Java注解(Annotation)

Java注解是附加在代码中的一些元信息,用于一些工具在编译、

运行时进行解析和使用,起到说明、配置的功能。

注解相关类都包含在java.lang.annotation包中。


2. Java注解分类

2.1 JDK基本注解

2.2 JDK元注解

2.3 自定义注解


3. JDK基本注解

  3.1 @Override

重写


  3.2 @Deprecated

已过时


  3.3 @SuppressWarnings(value = "unchecked")


压制编辑器警告



Java元注解

  作用:元注解用于修饰其他的注解

@Retention:定义注解的保留策略


@Retention(RetentionPolicy.SOURCE)            //注解仅存在于源码中,在class字节码文件中不包含      @Retention(RetentionPolicy.CLASS)              //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,      @Retention(RetentionPolicy.RUNTIME)            //注解会在class字节码文件中存在,在运行时可以通过反射获取到


@Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)


@Target(ElementType.TYPE)//接口、类@Target(ElementType.FIELD)//属性@Target(ElementType.METHOD)//方法@Target(ElementType.PARAMETER)//方法参数@Target(ElementType.CONSTRUCTOR)//构造函数@Target(ElementType.LOCAL_VARIABLE)//局部变量@Target(ElementType.ANNOTATION_TYPE)//注解@Target(ElementType.PACKAGE)//包

注:可以指定多个位置,例如:

@Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用


@Inherited:指定被修饰的Annotation将具有继承性


@Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.


自定义注解

注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):

标记Annotation:

没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息

元数据Annotation:

包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;

如何自定义注解?

使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:

Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,

而且我们还可以使用default关键字为这个成员变量设定默认值;


注意:只有名字为“value”属性,赋值时可以省略属性名


案例一(获取类与方法上的注解值):

TranscationModel

package com.huangting.annotation.P1;/** * enum枚举

*/publicenum  TranscationModel {

    Read, ReadWrite, Write

}

MyAnnotation1

package com.huangting.annotation.P1;importjava.lang.annotation.*;/** * MyAnnotation1注解可以用在类、接口、属性、方法上

* 注解运行期也保留

* 不可继承

*/@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic@interface MyAnnotation1 {

    String name();

}

MyAnnotation2

package com.huangting.annotation.P1;importjava.lang.annotation.*;/** *  MyAnnotation2注解可以用在方法上

*  注解运行期也保留

*  不可继承

*/@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic@interface MyAnnotation2 {

    TranscationModel model() default TranscationModel.ReadWrite;

}

   MyAnnotation3

package com.huangting.annotation.P1;importjava.lang.annotation.*;/** * MyAnnotation3注解可以用在方法上

* 注解运行期也保留

* 可继承

*/@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Inherited

@Documentedpublic@interface MyAnnotation3 {

    TranscationModel[] models() default TranscationModel.ReadWrite;

}

 Dome1

package com.huangting.annotation.P1;/** * 获取类与方法上的注解值

*/@MyAnnotation1(name = "abc")publicclass Demo1 {

    @MyAnnotation1(name = "xyz")

    private Integer age;

    @MyAnnotation2(model = TranscationModel.Read)

    publicvoid list() {

        System.out.println("list");

    }

    @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})

    publicvoid edit() {

        System.out.println("edit");

    }

}

Demo1Test

package com.huangting.annotation.P1;import org.junit.Test;publicclass Demo1Test {

    @Test

    publicvoidlist()throws Exception {//        获取类上的注解MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class);

        System.out.println(annotation1.name());//abc//        获取方法上的注解MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class);

        System.out.println(myAnnotation2.model());//Read    }

    @Test

    publicvoidedit()throws Exception {

        MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);

        for (TranscationModel model : myAnnotation3.models()) {

            System.out.println(model);//Read,Write        }

    }

}

效果:



 注意:

jar包的运用中最好不要出现test,把《scope》《/scope》删除即可

否则会报错@Test无法使用


案例二(获取类属性上的注解属性值)

TestAnnotation

package com.huangting.annotation.P2;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//@Retention(RetentionPolicy.SOURCE)@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.FIELD)public@interface TestAnnotation {

    String value() default"默认value值";

    String what() default"这里是默认的what属性对应的值";

}

Dome2

package com.huangting.annotation.P2;/** * 获取类属性上的注解属性值

*/publicclass Demo2 {

    @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")

    privatestatic String msg1;

    @TestAnnotation("这就是value对应的值1")

    privatestatic String msg2;

    @TestAnnotation(value = "这就是value对应的值2")

    privatestatic String msg3;

    @TestAnnotation(what = "这就是what对应的值")

    privatestatic String msg4;

}

Demo2Test

package com.huangting.annotation.P2;import org.junit.Test;publicclass Demo2Test {

    @Test

    publicvoidtest1()throws Exception {

        TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);

        System.out.println(msg1.value());

        System.out.println(msg1.what());

    }

    @Test

    publicvoidtest2()throws Exception{

        TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);

        System.out.println(msg2.value());

        System.out.println(msg2.what());

    }

    @Test

    publicvoidtest3()throws Exception{

        TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);

        System.out.println(msg3.value());

        System.out.println(msg3.what());

    }

    @Test

    publicvoidtest4()throws Exception{

        TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);

        System.out.println(msg4.value());

        System.out.println(msg4.what());

    }

}

效果:


案例三(获取参数修饰注解对应的属性值):

IsNotNull

package com.huangting.annotation.P3;importjava.lang.annotation.*;/** * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空

*/@Documented

@Target({ElementType.PARAMETER})

@Retention(RetentionPolicy.RUNTIME)public@interface IsNotNull {

    booleanvalue()defaultfalse;

}

Demo3

package com.huangting.annotation.P3;/** * 获取参数修饰注解对应的属性值

*/publicclass Demo3 {

    publicvoidhello1(@IsNotNull(true) String name) {

        System.out.println("hello:" + name);

    }

    publicvoid hello2(@IsNotNull String name) {

        System.out.println("hello:" + name);

    }

}

Demo3Test

package com.huangting.annotation.P3;import org.junit.Test;import java.lang.reflect.Parameter;publicclass Demo3Test {

    @Test

    publicvoidhello1()throws Exception {

        Demo3 demo3 =new Demo3();

        for(Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {

            IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);

            if(annotation !=null){

                System.out.println(annotation.value());//true            }

        }

    }

    @Test

    publicvoidhello2()throws Exception {

        Demo3 demo3 =new Demo3();

        for(Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {

            IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);

            if(annotation !=null){

                System.out.println(annotation.value());//false            }

        }

    }

}

效果:




Aop自定义注解的应用

 MyLog 

package com.huangting.annotation.Aop;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)public@interface MyLog {

    String desc();

}


MyLogAspect

package com.huangting.annotation.Aop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;

@Component

@Aspectpublicclass MyLogAspect {

    privatestaticfinalLogger logger = LoggerFactory.getLogger(MyLogAspect.class);

    /**    * 只要用到了com.huangting.annotation.Aop.MyLog这个注解的,就是目标类

    */    @Pointcut("@annotation(com.huangting.annotation.Aop.MyLog)")

    privatevoid MyValid() {

    }

    @Before("MyValid()")

    publicvoid before(JoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);

        System.out.println("[" + signature.getName() + " : start.....]");

        System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());

    }

}

BaseTestCase

package com.huangting.annotation.Aop;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})publicclass BaseTestCase {

}

LogController

package com.huangting.annotation.Aop;import org.springframework.stereotype.Component;

@Componentpublicclass LogController {

    @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")

    publicvoid testLogAspect(){

        System.out.println("墙头马上遥相顾");

    }

}

LogControllerTest

package com.huangting.annotation.Aop;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;publicclassLogControllerTestextends BaseTestCase {

    @Autowired

    private LogController logController;

    @Test

    publicvoid testLogAspect(){

        logController.testLogAspect();

    }

}

效果:

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341