java annotation aop_java之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

packagecom.huangting.annotation.P1;/*** enum枚举*/

public enumTranscationModel {

Read, ReadWrite, Write

}

MyAnnotation1

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

* 注解运行期也保留

* 不可继承*/@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic @interfaceMyAnnotation1 {

String name();

}

MyAnnotation2

packagecom.huangting.annotation.P1;import java.lang.annotation.*;/*** MyAnnotation2注解可以用在方法上

* 注解运行期也保留

* 不可继承*/@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic @interfaceMyAnnotation2 {

TranscationModel model()defaultTranscationModel.ReadWrite;

}

MyAnnotation3

packagecom.huangting.annotation.P1;import java.lang.annotation.*;/*** MyAnnotation3注解可以用在方法上

* 注解运行期也保留

* 可继承*/@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Inherited

@Documentedpublic @interfaceMyAnnotation3 {

TranscationModel[] models()defaultTranscationModel.ReadWrite;

}

Dome1

packagecom.huangting.annotation.P1;/*** 获取类与方法上的注解值*/@MyAnnotation1(name= "abc")public classDemo1 {

@MyAnnotation1(name= "xyz")privateInteger age;

@MyAnnotation2(model=TranscationModel.Read)public voidlist() {

System.out.println("list");

}

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

System.out.println("edit");

}

}

Demo1Test

packagecom.huangting.annotation.P1;importorg.junit.Test;public classDemo1Test {

@Testpublic void list() throwsException {//获取类上的注解

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}

@Testpublic void edit() throwsException {

MyAnnotation3 myAnnotation3= Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);for(TranscationModel model : myAnnotation3.models()) {

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

}

}

}

效果:

b9de557491d6ccef71ac32c7802b2f5b.png

注意:

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

d4376a22c39502d0fce5f159cb3c70f2.png

否则会报错@Test无法使用

83b227c4a56a9cb9f3fa9b4ffb641061.png

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

TestAnnotation

packagecom.huangting.annotation.P2;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;//@Retention(RetentionPolicy.SOURCE)

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.FIELD)public @interfaceTestAnnotation {

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

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

}

Dome2

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

public classDemo2 {

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

@TestAnnotation("这就是value对应的值1")private staticString msg2;

@TestAnnotation(value= "这就是value对应的值2")private staticString msg3;

@TestAnnotation(what= "这就是what对应的值")private staticString msg4;

}

Demo2Test

packagecom.huangting.annotation.P2;importorg.junit.Test;public classDemo2Test {

@Testpublic void test1() throwsException {

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

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

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

}

@Testpublic void test2() throwsException{

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

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

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

}

@Testpublic void test3() throwsException{

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

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

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

}

@Testpublic void test4() throwsException{

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

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

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

}

}

效果:

2a7112bc1e151147306449b956846abb.png

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

IsNotNull

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

@Target({ElementType.PARAMETER})

@Retention(RetentionPolicy.RUNTIME)public @interfaceIsNotNull {boolean value() default false;

}

Demo3

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

public classDemo3 {public void hello1(@IsNotNull(true) String name) {

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

}public voidhello2(@IsNotNull String name) {

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

}

}

Demo3Test

packagecom.huangting.annotation.P3;importorg.junit.Test;importjava.lang.reflect.Parameter;public classDemo3Test {

@Testpublic void hello1() throwsException {

Demo3 demo3= newDemo3();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

}

}

}

@Testpublic void hello2() throwsException {

Demo3 demo3= newDemo3();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

}

}

}

}

效果:

0dd18f848a55c39fa78f9d647cdbf42b.png

Aop自定义注解的应用

MyLog

packagecom.huangting.annotation.Aop;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)public @interfaceMyLog {

String desc();

}

MyLogAspect

packagecom.huangting.annotation.Aop;importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Before;importorg.aspectj.lang.annotation.Pointcut;importorg.aspectj.lang.reflect.MethodSignature;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.stereotype.Component;

@Component

@Aspectpublic classMyLogAspect {private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);/*** 只要用到了com.huangting.annotation.Aop.MyLog这个注解的,就是目标类*/@Pointcut("@annotation(com.huangting.annotation.Aop.MyLog)")private voidMyValid() {

}

@Before("MyValid()")public voidbefore(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

packagecom.huangting.annotation.Aop;importorg.junit.runner.RunWith;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})public classBaseTestCase {

}

LogController

packagecom.huangting.annotation.Aop;importorg.springframework.stereotype.Component;

@Componentpublic classLogController {

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

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

}

}

LogControllerTest

packagecom.huangting.annotation.Aop;importorg.junit.Test;importorg.springframework.beans.factory.annotation.Autowired;public class LogControllerTest extendsBaseTestCase {

@AutowiredprivateLogController logController;

@Testpublic voidtestLogAspect(){

logController.testLogAspect();

}

}

效果:

71559dd3254cafb0e50df67db0ab78df.png

谢谢观看!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值