java自定义注解介绍
本篇博客主要介绍以下几点内容
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将具有继承性
自定义注解
注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):
标记Annotation:
没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息
元数据Annotation:
包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;
如何自定义注解?
使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:
Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,
而且我们还可以使用default关键字为这个成员变量设定默认值;
注意:只有名字为“value”属性,赋值时可以省略属性名
详细代码
案例一(获取类与方法上的注解值):
junit 作用改变 在pom改变
MyAnnotation1
package com.wxm.annotation.p1;
import java.lang.annotation.*;
/**
*
* MyAnnotation1注解可以用在类、接口、属性、方法上
* 注解运行期也保留
* 不可继承
*/
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
String name();
}
MyAnnotation2
package com.wxm.annotation.p1;
import java.lang.annotation.*;
/**
*
* MyAnnotation2注解可以用在方法上
* 注解运行期也保留
* 不可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
TranscationModel model() default TranscationModel.ReadWrite;
}
MyAnnotation3
package com.wxm.annotation.p1;
import java.lang.annotation.*;
/**
*
* MyAnnotation3注解可以用在方法上
* 注解运行期也保留
* 可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
TranscationModel[] models() default TranscationModel.ReadWrite;
}
TestAnnotation
package com.wxm.annotation.p1;
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属性对应的值";
}
TranscationModel
package com.wxm.annotation.p1;
/**
* @author
* @site
* @company
* @create
*/
public enum TranscationModel {
Read, Write, ReadWrite
}
效果:
案例二(获取类属性上的注解属性值)
Demo2
package com.wxm.annotation.p1.p2;
/**
*
* 获取类属性上的注解属性值
*/
public class Demo2 {
@TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
private static String msg1;
@TestAnnotation("这就是value对应的值1")
private static String msg2;
@TestAnnotation(value = "这就是value对应的值2")
private static String msg3;
@TestAnnotation(what = "这就是what对应的值")
private static String msg4;
}
test1
test2
test3
test4
案例三(获取参数修饰注解对应的属性值):
IsNotNull
package com.wxm.annotation.p1.p3;
import java.lang.annotation.*;
/**
*
* 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
*/
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
boolean value() default false;
}
测试结果:
示例二:@Target(ElementType.TYPE、METHOD、FIELD)三个作用域的示例
myName (自定义注解类)
package com.wxm.annotation.p1.p4;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2019-12-26 14:30
*/
public class myName {
@FieldAnnotation
private String name;
@FieldAnnotation(description = "这是描述:我们都爱打王者!!!")
private String description;
@MethodAnnotation
public String getString(){
return "一起开黑!!!!";
}
}
ClassAnnotation
package com.wxm.annotation.p1.p4;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2019-12-26 14:25
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ClassAnnotation {
int age() default 18;
}
FieldAnnotation
package com.wxm.annotation.p1.p4;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2019-12-26 14:29
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
String name() default "小明";
String description() default "爱唱歌";
}
MethodAnnotation
package com.wxm.annotation.p1.p4;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2019-12-26 14:27
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodAnnotation {
String value() default "爱打豆豆";
String name() default "李华";
}
测试类:
package com.wxm.annotation.p1.p4;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2019-12-26 14:33
*/
@ClassAnnotation(age = 25)
public class Test {
/**
* Class注解测试
*
* @param c
*/
public static void test1(Class<?> c) {
ClassAnnotation ca = c.getAnnotation(ClassAnnotation.class);
if (ca == null) {
System.out.println("这里啥都没有");
} else {
System.out.println("Class注解:age:" + ca.age());
}
}
/**
* Method注解测试
*
* @param c
*/
public static void test2(Class<?> c) {
Method[] method = c.getDeclaredMethods();
for (Method me : method) {
MethodAnnotation methodAnnotation = me.getAnnotation(MethodAnnotation.class);
if (methodAnnotation == null) {
System.out.println("这里啥都没有");
} else {
System.out.println("方法注解的name:" + methodAnnotation.name());
System.out.println("方法注解的value" + methodAnnotation.value());
}
}
}
/**
* Field注解测试
*
* @param c
*/
public static void test3(Class<?> c) {
Field[] fields = c.getDeclaredFields();
System.out.println("被注解FieldAnnotation注解的属性:");
for (Field f :
fields) {
System.out.println("------------------");
System.out.println("属性名称:" + f.getName());
descFiledInfo(f);
}
}
/**
* 分别获取注解的详细信息
*
* @param field
*/
private static void descFiledInfo(Field field) {
FieldAnnotation fa = field.getAnnotation(FieldAnnotation.class);
if (fa == null) {
System.out.println("这里啥都没有");
} else {
System.out.println("分别获取注解的详细信息:name:" + fa.name());
System.out.println("分别获取注解的详细信息:descp:" + fa.description());
}
}
public static void main(String[] args) {
Test.test1(Test.class);
Test.test2(myName.class);
System.out.println("===================================");
Test.test3(myName.class);
}
}
测试结果:
总结:
注解作用在类上:用类名可以直接点出getAnnotation(xxx.class)方法,方法参数可以直接填写注解那个类;
注解作用在方法上:用类名可以直接点出getDeclaredMethods()方法,获取所有用注解注释的方法名称,在通过所得到的方法名称来获取
注解作用在属性上:用类名可以直接点出c.getDeclaredFields()方法,获取所有用注解注释的属性名称,在通过所得到属性名称来获取对应的注解类;
Aop自定义注解的应用日志监控
LogController
package com.wxm.annotation.p1.log;
import org.springframework.stereotype.Component;
@Component
public class LogController {
@MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
public void testLogAspect(){
System.out.println("这里随便来点啥");
}
}
MyLog
package com.wxm.annotation.p1.log;
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.wxm.annotation.p1.log;
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
@Aspect
public class MyLogAspect {
private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
/**
* 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类
*/
@Pointcut("@annotation(com.wxm.annotation.p1.log.MyLog)")
private void MyValid() {
}
@Before("MyValid()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
logger.debug("[" + signature.getName() + " : start.....]");
MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());
}
}
这是你Mylog 是目标类的路径
test层
package log;
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"})
public class BaseTestCase {
}
LogControllerTest
package log;
import com.wxm.annotation.p1.log.LogController;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class LogControllerTest extends BaseTestCase {
@Autowired
private LogController logController;
@Test
public void testLogAspect(){
logController.testLogAspect();
}
}
测试结果: