SpringAOP02 自定义注解
1 自定义注解
1.1 创建自定义注解
从java5开始就可以利用 @interface 来定义自定义注解
技巧01:注解不能直接干扰程序代码的运行(即:注解的增加和删除操作后,代码都可以正常运行)
技巧02:@Retention 用来声明注解的保留期限
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/ package java.lang.annotation; /**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE, /**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS, /**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
RetentionPolicy.java
技巧03:@Target 用来声明使用该注解的目标类型
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/ package java.lang.annotation; /**
* The constants of this enumerated type provide a simple classification of the
* syntactic locations where annotations may appear in a Java program. These
* constants are used in {@link Target java.lang.annotation.Target}
* meta-annotations to specify where it is legal to write annotations of a
* given type.
*
* <p>The syntactic locations where annotations may appear are split into
* <em>declaration contexts</em> , where annotations apply to declarations, and
* <em>type contexts</em> , where annotations apply to types used in
* declarations and expressions.
*
* <p>The constants {@link #ANNOTATION_TYPE} , {@link #CONSTRUCTOR} , {@link
* #FIELD} , {@link #LOCAL_VARIABLE} , {@link #METHOD} , {@link #PACKAGE} ,
* {@link #PARAMETER} , {@link #TYPE} , and {@link #TYPE_PARAMETER} correspond
* to the declaration contexts in JLS 9.6.4.1.
*
* <p>For example, an annotation whose type is meta-annotated with
* {@code @Target(ElementType.FIELD)} may only be written as a modifier for a
* field declaration.
*
* <p>The constant {@link #TYPE_USE} corresponds to the 15 type contexts in JLS
* 4.11, as well as to two declaration contexts: type declarations (including
* annotation type declarations) and type parameter declarations.
*
* <p>For example, an annotation whose type is meta-annotated with
* {@code @Target(ElementType.TYPE_USE)} may be written on the type of a field
* (or within the type of the field, if it is a nested, parameterized, or array
* type), and may also appear as a modifier for, say, a class declaration.
*
* <p>The {@code TYPE_USE} constant includes type declarations and type
* parameter declarations as a convenience for designers of type checkers which
* give semantics to annotation types. For example, if the annotation type
* {@code NonNull} is meta-annotated with
* {@code @Target(ElementType.TYPE_USE)}, then {@code @NonNull}
* {@code class C {...}} could be treated by a type checker as indicating that
* all variables of class {@code C} are non-null, while still allowing
* variables of other classes to be non-null or not non-null based on whether
* {@code @NonNull} appears at the variable's declaration.
*
* @author Joshua Bloch
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 4.1 The Kinds of Types and Values
*/
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE, /** Field declaration (includes enum constants) */
FIELD, /** Method declaration */
METHOD, /** Formal parameter declaration */
PARAMETER, /** Constructor declaration */
CONSTRUCTOR, /** Local variable declaration */
LOCAL_VARIABLE, /** Annotation type declaration */
ANNOTATION_TYPE, /** Package declaration */
PACKAGE, /**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER, /**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
ElementType.java
坑01:自定义注解允许定义成员,但是这里的成员在进行声明时必须是无入参、无抛出异常的方式进行声明;而且成员只能是方法
坑02:在给成员指定默认值是必须使用default关键字
package cn.test.demo.base_demo.annotations; 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.METHOD)
public @interface NeedTest {
boolean value() default true;
}
1.2 使用注解
1.2.1 创建一个SrpingBoot项目
下载地址:点击前往
1.2.2 新建一个自定义注解类
package cn.test.demo.base_demo.annotations; 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.METHOD)
public @interface NeedTest {
boolean value() default true;
}
NeedTest.java
1.2.3 新建一个服务类
在该服务类的方法中使用刚刚创建的自定义注解
package cn.test.demo.base_demo.service; import cn.test.demo.base_demo.annotations.NeedTest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; /**
* @author 王杨帅
* @create 2018-04-29 21:31
* @desc 学生服务类
**/
@Service
@Slf4j
public class StudentService { private final String className = getClass().getName(); @NeedTest()
public void insert() {
log.info("===/" + className + "/insert===新增操作");
} @NeedTest(value = false)
public void delete() {
log.info("===/" + className + "/delete===删除操作");
} }
StudentService.java
1.2.4 访问注解
从Java5开始包、类、构造器、方法、字段等都反射对象都开始支持访问注解信息的方法
/**
* {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @since 1.5
*/
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return super.getAnnotation(annotationClass);
}
package cn.test.demo.base_demo.service; import cn.test.demo.base_demo.annotations.NeedTest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import java.lang.reflect.Method; import static org.junit.Assert.*; @RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class StudentServiceTest { private final String className = getClass().getName(); @Test
public void test01() {
Class cla = StudentService.class;
Method[] methods = cla.getDeclaredMethods();
log.info("===/" + className + "/test01===方法数量为:{}", methods.length);
for (Method method : methods) {
NeedTest nt = method.getAnnotation(NeedTest.class);
if (nt.value()) {
log.info("===" + method.getName() + "()需要测试");
} else {
log.info("===" + method.getName() + "()不需要进行测试");
} }
} @Test
public void insert() throws Exception {
} @Test
public void delete() throws Exception {
} }
StudentServiceTest.java
SpringAOP02 自定义注解的更多相关文章
- java自定义注解类
一.前言 今天阅读帆哥代码的时候,看到了之前没有见过的新东西, 比如java自定义注解类,如何获取注解,如何反射内部类,this$0是什么意思? 于是乎,学习并整理了一下. 二.代码示例 import ...
- Jackson 通过自定义注解来控制json key的格式
Jackson 通过自定义注解来控制json key的格式 最近我这边有一个需求就是需要把Bean中的某一些特殊字段的值进行替换.而这个替换过程是需要依赖一个第三方的dubbo服务的.为了使得这个转换 ...
- 自定义注解之运行时注解(RetentionPolicy.RUNTIME)
对注解概念不了解的可以先看这个:Java注解基础概念总结 前面有提到注解按生命周期来划分可分为3类: 1.RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成clas ...
- JAVA自定义注解
在学习使用Spring和MyBatis框架的时候,使用了很多的注解来标注Bean或者数据访问层参数,那么JAVA的注解到底是个东西,作用是什么,又怎样自定义注解呢?这篇文章,即将作出简单易懂的解释. ...
- 用大白话聊聊JavaSE -- 自定义注解入门
注解在JavaSE中算是比较高级的一种用法了,为什么要学习注解,我想大概有以下几个原因: 1. 可以更深层次地学习Java,理解Java的思想. 2. 有了注解的基础,能够方便阅读各种框架的源码,比如 ...
- [javaSE] 注解-自定义注解
注解的分类: 源码注解 编译时注解 JDK的@Override 运行时注解 Spring的@Autowired 自定义注解的语法要求 ① 使用@interface关键字定义注解 ② 成员以无参无异常方 ...
- 使用spring aspect控制自定义注解
自定义注解:这里是一个处理异常的注解,当调用方法发生异常时,返回异常信息 /** * ErrorCode: * * @author yangzhenlong * @since 2016/7/21 */ ...
- ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存
基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...
- Java 自定义注解
在spring的应用中,经常使用注解进行开发,这样有利于加快开发的速度. 介绍一下自定义注解: 首先,自定义注解要新建一个@interface,这个是一个注解的接口,在此接口上有这样几个注解: @Do ...
随机推荐
- [Luogu1527][国家集训队]矩阵乘法
luogu 题意 给你一个\(N*N\)的矩阵,每次询问一个子矩形的第K小数.(居然连修改都不带的) \(N\le500,Q\le60000\) sol 整体二分+二维树状数组裸题. 复杂度是\(O( ...
- var ev = ev || event
event是事件对象(也是window的属性),但不是标准的,只有IE支持. 在W3C标准支持的浏览器下事件对象是引发事件函数的第一个参数,参数名随意. 所以,我们一般使用事件对象: function ...
- dockerfile初试之tomcat8封装
前面学习了一些docker相关资料,有看到dockerfile这个东东,一时没看得太明白,理论给合实践是最好的学习方法,自己做一下就行了嘛.主要步聚记录如下: 0)环境 10.202.105.96 ...
- Python学习笔记之selenium 定制启动 chrome 的选项
在自动化中,默认情况下我们打开的就是一个普通的纯净的chrome浏览器,而我们平时在使用浏览器时,经常就添加一些插件,扩展,代理之类的应用.所以使用 selenium 时,我们可能需要对 chrome ...
- FIR数字信号滤波器
数字滤波器 在信号处理领域中,对于信号处理的实时性.快速性的要求越来越高.而在许多信息处理过程中,如对信号的过滤.检测.预测等,都要广泛地用到滤波器. 其中数字滤波器具有稳定性高.精度高.设计灵活.实 ...
- java代码----求最大值,平均值。。。
总结:方法的返回值----返回的对象到底是什么? package com.a; import java.util.Scanner; //从键盘输入10个数,并输出最大值,最小值,平均值 public ...
- 网络编程Socket之wireshark使用
这里只对wireshark进行简单的使用介绍.里面的报表,IO图形分析等以后再谈.... 这里不提供下载地址了,不是什么稀有资源,我使用的wireshark是在百度软件中心下载的. 第一步:选择需要 ...
- win7 网站发布备注
1.更改 .NET Framework 版本(改原设置v2.0 为v4.0) 2.程序池设置 3.基本设置 4.Web.config (debug="false") <sys ...
- Py修行路 python基础 (十六)面向对象编程的 继承 多态与多态性 封装
一.继承顺序: 多继承情况下,有两种方式:深度优先和广度优先 1.py3/py2 新式类的继承:在查找属性时遵循:广度优先 继承顺序是多条分支,按照从左往右的顺序,进行一步一步查找,一个分支走完会走另 ...
- leetcode905
vector<int> sortArrayByParity(vector<int>& A) { vector<int> EVEN;//偶数 vector&l ...