1.注解简介
1.1.什么是注解
Annotation是从JDK5.0开始引入的新技术
Annotation的作用
不是程序本身,可以对程序做出解释(这一点和注释(comment)没有什么区别)
可以被其他程序(比如: 编译器等) 读取
Annotation的格式
注解是以“@注释名”在代码中存在的,还可以添加一些参数值,例如: @SuppressWarnings(value=“unchecked”)
Annotation在哪里使用?
可以附加在package,class,method,field等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问
1.2.内置注解
@Override:定义在java.lang.Override中,此注释只适用于修饰方法,表示一个方法打算重写超类中的另一个方法声明
@Deprecated: 定义在java.lang.Deprecated中,此注解用于修饰方法,属性,类,表示不鼓励程序员使用这样的元素,通常是因为它很危险或者存在更好的选择
@SuppressWarnings:定义在java.lang.SuppressWarnings中,用来抑制编译时的警告信息
与前两个注解有所不同,需要添加一个参数才能正确使用,这些参数都是已经定义好了的,我们选择性的使用就好了
@SuppressWarnings(“all”)
@SuppressWarnings(“unchecked”)
@SuppressWarnings(value={“unchecked”,“deprecation”})
等等
1.3.元注解
元注解的作用就是负责注解其他注解,Java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型作说明
这些类型和它们所支持的类在java.lang.annotation包中可以找到(@Target,@Retention,@Documented,@Inherited)
@Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
@Retention:表示需要在什么级别保存注释信息,用于描述注解的生命周期(Source<class<Runtime)
@Document: 说明该注解将被包含在javaDoc中
@Inherited:说明子类可以继承父类中的该注解
1.4.自定义注解
使用@interface自定义注解时,自动继承了java.lang.Annotation接口
分析
@interface用来声明一个注解,格式:public @interface 注解名{定义内容}
其中的每一个方法实际上是声明了一个配置参数
方法的名称就是参数的名称
返回值的类型就是参数的类型(返回值只能是基本类型,Class,String ,enum)
可以通过default来声明参数的默认值
如果只有一个参数成员,一般参数名为value
注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值
2编写自定义注解
2.1.创建SpringBoot项目
PS: 后面还要使用到, 所以这里创建一个空的项目,通过创建模块的方式完成
2.2创建好项目,修改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spboot01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spboot01</name>
<description>spboot01</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!-- <scope>test</scope>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.案例一
3.1.新建一个annotation包
3.2.添加TranscationModel枚举类
package com.example.spboot01.annotation;
public enum TranscationModel {
Read, Write, ReadWrite
}
3.3.新建MyAnnotation1注解
package com.example.spboot01.annotation;
import java.lang.annotation.*;
/**
* MyAnnotation1注解可以用在类、接口、属性、方法上
* 注解运行期也保留
* 不可继承
*/
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public interface MyAnnotation1 {
String name();
}
3.4.新建MyAnnotation2注解
package com.example.spboot01.annotation.demo01;
import java.lang.annotation.*;
/**
* MyAnnotation2注解可以用在方法上
* 注解运行期也保留
* 不可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
TranscationModel model() default TranscationModel.ReadWrite;
}
3.5.新建MyAnnotation3注解
package com.example.spboot01.annotation.demo01;
import java.lang.annotation.*;
/**
* MyAnnotation3注解可以用在方法上
* 注解运行期也保留
* 可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
TranscationModel[] models() default TranscationModel.ReadWrite;
}
3.6.新建Demo类
package com.example.spboot01.annotation.demo01;
/**
* 获取类与方法上的注解值
*/
@MyAnnotation1(name = "abc")
public class Demo1 {
@MyAnnotation1(name = "xyz")
private Integer age;
@MyAnnotation2(model = TranscationModel.Read)
public void list() {
System.out.println("list");
}
@MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
public void edit() {
System.out.println("edit");
}
}
3.7.新建DemoTest类
package com.example.spboot01.annotation.demo01;
import org.junit.Test;
public class Demo1Test {
@Test
public void list() 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
// 获取属性上的注解
MyAnnotation1 myAnnotation1 = Demo1.class.getDeclaredField("age").getAnnotation(MyAnnotation1.class);
System.out.println(myAnnotation1.name());// xyz
}
@Test
public void edit() throws Exception {
MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);
for (TranscationModel model : myAnnotation3.models()) {
System.out.println(model);//Read,Write
}
}
}
3.8.运行结果
4. 案例二
4.1.新建demo02包
4.2.新建TestAnnotation注解
package com.example.spboot01.annotation.demo02;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
String value() default "默认value值";
String what() default "这里是默认的what属性对应的值";
}
4.3.新建Demo2类
package com.example.spboot01.annotation.demo02;
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;
}
4.4.新建Demo2Test
package com.example.spboot01.annotation.demo02;
import org.junit.Test;
public class Demo2Test {
@Test
public void test1() throws Exception {
TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
System.out.println(msg1.value());
System.out.println(msg1.what());
}
@Test
public void test2() throws Exception {
TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
System.out.println(msg2.value());
System.out.println(msg2.what());
}
@Test
public void test3() throws Exception {
TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
System.out.println(msg3.value());
System.out.println(msg3.what());
}
@Test
public void test4() throws Exception {
TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
System.out.println(msg4.value());
System.out.println(msg4.what());
}
}
4.5运行结果
5.案例三(获取参数修饰注解对应的属性值)
5.1.demo03.class
package com.example.spboot01.annotation.demo03;
public class Demo3 {
public void hello1(@IsNotNull(true) String name) {
System.out.println("hello:" + name);
}
public void hello2(@IsNotNull String name) {
System.out.println("hello:" + name);
}
}
5.2.IsNotNull.interface
package com.example.spboot01.annotation.demo03;
import java.lang.annotation.*;
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
boolean value() default false;
}
5.3.demo3Test.class
package com.example.spboot01.annotation.demo03;
import org.junit.Test;
import java.lang.reflect.Parameter;
public class Demo3Test {
@Test
public void hello1() 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
public void hello2() 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
}
}
}
}
6.Aop自定义注解的应用
6.1.在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
6.2.自定义注解
package com.example.spboot01.annotation.aopDemo;
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();
}
6.3.定义切面类
package com.example.spboot01.annotation.aopDemo;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
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.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
public class MyLogAspect {
private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
/**
* 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类
*/
@Pointcut("@annotation(com.example.spboot01.annotation.aopDemo.MyLog)")
private void MyValid() {
}
@Before("MyValid()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
logger.debug("[" + signature.getName() + " : start.....]");
System.out.println("[" + signature.getName() + " : start.....]");
MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());
System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
}
}
6.4.新建LogController
package com.example.spboot01.annotation.aopDemo;
import org.springframework.stereotype.Component;
@Component
public class LogController {
@MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
public void testLogAspect(){
System.out.println("这里随便来点啥");
}
}
6.5.新建LogControllerTest
package com.example.spboot01.annotation.aopDemo;
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();
}
}
6.6.MyLogAspect中添加内容
@Around("MyValid()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object[] args = pjp.getArgs();
System.out.println(Arrays.toString(args));
Object ob = pjp.proceed();// ob 为方法的返回值
System.out.println("耗时 : " + (System.currentTimeMillis() - startTime) + "ms");
return ob;
}
6.7.修改LogController.java
package com.example.spboot01.annotation.aopDemo;
import org.springframework.stereotype.Component;
@Component
public class LogController {
@MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
public void testLogAspect(String name, int age) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("这里随便来点啥");
}
}
6.8.修改LogControllerTest.java
package com.example.spboot01.annotation.aopDemo;
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("张三", 18);
}
}