- 自定义注解简介
- 自定义注解基本案例
- aop自定义注解
1.自定义注解简介
1.基本注解
2.元注解
3.自定义注解
3.1.标记注解
3.2.元数据注解
3.3.自定义注解语法:@interface
JDK基本注解
@Override
重写
@SuppressWarnings(value = "unchecked")
压制编辑器警告
JDK元注解
@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关键字为这个成员变量设定默认值;
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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>zljzyssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>zljzyssm Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version> <!--添加jar包依赖--> <!--1.spring 5.0.2.RELEASE相关--> <spring.version>5.0.2.RELEASE</spring.version> <!--2.mybatis相关--> <mybatis.version>3.4.5</mybatis.version> <!--mysql--> <mysql.version>5.1.44</mysql.version> <!--pagehelper分页jar依赖--> <pagehelper.version>5.1.2</pagehelper.version> <!--mybatis与spring集成jar依赖--> <mybatis.spring.version>1.3.1</mybatis.spring.version> <!--3.dbcp2连接池相关 druid--> <commons.dbcp2.version>2.1.1</commons.dbcp2.version> <commons.pool2.version>2.4.3</commons.pool2.version> <!--4.log日志相关--> <log4j2.version>2.9.1</log4j2.version> <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version> <slf4j.version>1.7.13</slf4j.version> <!--5.其他--> <junit.version>4.12</junit.version> <servlet.version>4.0.0</servlet.version> <lombok.version>1.18.2</lombok.version> <mybatis.ehcache.version>1.1.0</mybatis.ehcache.version> <ehcache.version>2.10.0</ehcache.version> <redis.version>2.9.0</redis.version> <redis.spring.version>1.7.1.RELEASE</redis.spring.version> <jackson.version>2.9.3</jackson.version> <jstl.version>1.2</jstl.version> <standard.version>1.1.2</standard.version> <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version> <commons-fileupload.version>1.3.3</commons-fileupload.version> <hibernate-validator.version>5.0.2.Final</hibernate-validator.version> <shiro.version>1.3.2</shiro.version> </properties> <dependencies> <!--1.spring相关--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--2.mybatis相关--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--pagehelper分页插件jar包依赖--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!--mybatis与spring集成jar包依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!--mybatis与ehcache整合--> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>${mybatis.ehcache.version}</version> </dependency> <!--ehcache依赖--> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${redis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${redis.spring.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!--3.dbcp2连接池相关--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${commons.dbcp2.version}</version> <exclusions> <exclusion> <artifactId>commons-pool2</artifactId> <groupId>org.apache.commons</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons.pool2.version}</version> </dependency> <!--springmvc依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--4.log日志相关依赖--> <!-- log4j2日志相关依赖 --> <!-- log配置:Log4j2 + Slf4j --> <!-- slf4j核心包--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!--核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <!--用于与slf4j保持桥接--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> </dependency> <!--web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j2.version}</version> <scope>runtime</scope> </dependency> <!--需要使用log4j2的AsyncLogger需要包含disruptor--> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>${log4j2.disruptor.version}</version> </dependency> <!--5.其他--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <!-- <scope>test</scope>--> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${standard.version}</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>${tomcat-jsp-api.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> </dependency> <!--shiro依赖--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> </dependencies> <build> <finalName>zljzyssm</finalName> <resources> <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> <resource> <directory>src/main/resources</directory> <includes> <include>jdbc.properties</include> <include>*.xml</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.plugin.version}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> </project>
package com.zlj.annotation.demo1; public enum TranscationModel { Read, Write, ReadWrite; private String name; private Integer id; public void init1(){ Read.id=1; Read.name="zs"; } public void init2(){ Write.id=2; Write.name="ls"; } public void init3(){ ReadWrite.id=3; ReadWrite.name="ww"; } }
package com.zlj.annotation.demo1; import java.lang.annotation.*; /** * MyAnnotation1注解可以用在类、接口、属性、方法上 * 注解运行期也保留 * 不可继承 */ @Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation1 { String name(); }
package com.zlj.annotation.demo1; import java.lang.annotation.*; /** * MyAnnotation2注解可以用在方法上 * 注解运行期也保留 * 不可继承 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation2 { TranscationModel model() default TranscationModel.ReadWrite; }
package com.zlj.annotation.demo1; import java.lang.annotation.*; /** * MyAnnotation3注解可以用在方法上 * 注解运行期也保留 * 可继承 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited //继承使用时需要该注解,否则读取不到该继承的注解及属性 @Documented public @interface MyAnnotation3 { TranscationModel[] models() default TranscationModel.ReadWrite; }
package com.zlj.annotation; import com.zlj.annotation.demo1.TranscationModel; /** * @author zlj * @create 2023-09-14 19:32 */ public class Test1 { public static void main(String[] args) { System.out.println(TranscationModel.Read); System.out.println(TranscationModel.Write); System.out.println(TranscationModel.ReadWrite); } }
package com.zlj.annotation; import com.zlj.annotation.demo1.MyAnnotation1; import com.zlj.annotation.demo1.MyAnnotation2; import com.zlj.annotation.demo1.MyAnnotation3; import com.zlj.annotation.demo1.TranscationModel; /** * * 获取类与方法上的注解值 */ @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"); } }
package com.zlj.annotation; import com.zlj.annotation.demo1.MyAnnotation1; import com.zlj.annotation.demo1.MyAnnotation2; import com.zlj.annotation.demo1.MyAnnotation3; import com.zlj.annotation.demo1.TranscationModel; import org.junit.Test; /** * @site www.javaxl.com */ 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 } } }
案例二
package com.zlj.annotation.demo2; /** * @site www.javaxl.com * * 获取类属性上的注解属性值 */ public class Demo2 { @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1") private static String msg1; //当没有在注解中指定属性名,那么就是value @TestAnnotation("这就是value对应的值1") private static String msg2; @TestAnnotation(value = "这就是value对应的值2") private static String msg3; @TestAnnotation(what = "这就是what对应的值") private static String msg4; }
package com.zlj.annotation.demo2; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @site www.javaxl.com */ //@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface TestAnnotation { String value() default "默认value值"; String what() default "这里是默认的what属性对应的值"; }
package com.zlj.annotation.demo2; import org.junit.Test; /** * @site www.javaxl.com */ 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()); } }
总结:在Demo2中如果指定了value和what值,那么在DemoTest2运行结果就是Demo2里的value和what值;
在Demo2中如果没有在注解中指定属性名,那么就是value,在DemoTest2运行结果就是Demo2的value值和TestAnnotation里的what值;
在Demo2中如果只指定了value值,在DemoTest2运行结果也是Demo2的value值和TestAnnotation里的what值;
在Demo2中如果只指定了what值,在DemoTest2运行结果就是TestAnnotation里的value值和Demo2的what值;
方案三
package com.zlj.annotation.demo3; import java.lang.annotation.*; /** * @author zlj * @site www.javaxl.com * * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空 */ @Documented @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface IsNotNull { boolean value() default false; }
package com.zlj.annotation.demo3; /** * @author zlj * @site www.javaxl.com * * 获取参数修饰注解对应的属性值 */ 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); } }
package com.zlj.annotation.demo3; import org.junit.Test; import java.lang.reflect.Method; import java.lang.reflect.Parameter; /** * @author zlj * @site www.javaxl.com */ 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 } } } @Test public void hello3() throws Exception { // 模拟浏览器传递到后台的参数 解读@requestParam String name = "zs"; Demo3 demo3 = new Demo3(); Method method = demo3.getClass().getMethod("hello1", String.class); for (Parameter parameter : method.getParameters()) { IsNotNull annotation = parameter.getAnnotation(IsNotNull.class); if(annotation != null){ System.out.println(annotation.value());//true if (annotation.value() && !"".equals(name)){ method.invoke(demo3,name); } } } } }
注解案例知识点:
1.获取类,方法,属性,修饰参数上的注解
2.关于注解上的value属性设置值是可以省略的
3.Inhereted案例演示,体现类上面的注解的继承性
4.default值的使用
3.aop自定义注解
package com.zlj.annotation.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author zlj * @site www.javaxl.com */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyLog { String desc(); }
package com.zlj.web; import com.zlj.annotation.aop.MyLog; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author zlj * @site www.javaxl.com */ @Controller public class LogController { @RequestMapping("/mylog") @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例") public void testLogAspect(){ System.out.println("这里随便来点啥"); } }
package com.zlj.aspect; import com.zlj.annotation.aop.MyLog; 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; /** * @author zlj * @site www.javaxl.com */ @Component @Aspect public class MyLogAspect { private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class); /** * 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类 * * *..Biz. *pager(..) * execution */ @Pointcut("@annotation(com.zlj.annotation.aop.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()); } }