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 自定义注解的更多相关文章

  1. java自定义注解类

    一.前言 今天阅读帆哥代码的时候,看到了之前没有见过的新东西, 比如java自定义注解类,如何获取注解,如何反射内部类,this$0是什么意思? 于是乎,学习并整理了一下. 二.代码示例 import ...

  2. Jackson 通过自定义注解来控制json key的格式

    Jackson 通过自定义注解来控制json key的格式 最近我这边有一个需求就是需要把Bean中的某一些特殊字段的值进行替换.而这个替换过程是需要依赖一个第三方的dubbo服务的.为了使得这个转换 ...

  3. 自定义注解之运行时注解(RetentionPolicy.RUNTIME)

    对注解概念不了解的可以先看这个:Java注解基础概念总结 前面有提到注解按生命周期来划分可分为3类: 1.RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成clas ...

  4. JAVA自定义注解

    在学习使用Spring和MyBatis框架的时候,使用了很多的注解来标注Bean或者数据访问层参数,那么JAVA的注解到底是个东西,作用是什么,又怎样自定义注解呢?这篇文章,即将作出简单易懂的解释. ...

  5. 用大白话聊聊JavaSE -- 自定义注解入门

    注解在JavaSE中算是比较高级的一种用法了,为什么要学习注解,我想大概有以下几个原因: 1. 可以更深层次地学习Java,理解Java的思想. 2. 有了注解的基础,能够方便阅读各种框架的源码,比如 ...

  6. [javaSE] 注解-自定义注解

    注解的分类: 源码注解 编译时注解 JDK的@Override 运行时注解 Spring的@Autowired 自定义注解的语法要求 ① 使用@interface关键字定义注解 ② 成员以无参无异常方 ...

  7. 使用spring aspect控制自定义注解

    自定义注解:这里是一个处理异常的注解,当调用方法发生异常时,返回异常信息 /** * ErrorCode: * * @author yangzhenlong * @since 2016/7/21 */ ...

  8. ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存

    基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...

  9. Java 自定义注解

    在spring的应用中,经常使用注解进行开发,这样有利于加快开发的速度. 介绍一下自定义注解: 首先,自定义注解要新建一个@interface,这个是一个注解的接口,在此接口上有这样几个注解: @Do ...

随机推荐

  1. ESLint在vue中的使用

    ESLint的用途 1.审查代码是否符合编码规范和统一的代码风格: 2.审查代码是否存在语法错误:  中文网地址 http://eslint.cn/ 使用VSCode编译器在Vue项目中的使用 在初始 ...

  2. zend studio 提升开发效率的快捷键及可视化订制相关设置

    Zend studio快捷键使用 F3 快速跳转到当前所指的函数,常量,方法,类的定义处,相当常用.当然还可以用Ctrl+鼠标左键 shift+end 此行第一个到最后一个 shift+home 此行 ...

  3. (转)android adb pull and push

    adb命令下pull的作用是从手机端向电脑端拷文件. 命令:adb pull /sdcard/**.txt   D:\                          说明:将手机卡中的某个文本文件 ...

  4. 关于IO流的抽象类

    被一个问题问愣了:java的IO里有哪些抽象类?这个一时半会儿还真记不得,只知道IO有好几类,具体有哪些抽象类从来没有去认真记过.回头仔细看了下分类和继承才发现其实就两对:字节流的抽象类是InputS ...

  5. 不常用的linux命令

    不太常用的命令 vipw          ##打开密码配置文件 dmesg       ##补充说明:kernel会将开机信息存储在ring buffer中.您若是开机时来不及查看信息,可利用dme ...

  6. 程序或-内存区域分配& ELF分析 ***

    一.在学习之前我们先看看ELF文件. ELF分为三种类型: 1. .o 可重定位文件(relocalble file) 2. 可执行文件 3. 共享库(shared library) 三种格式基本上从 ...

  7. 对于global的介绍

    抄自http://veniceweb.googlecode.com/svn/trunk/public/daily_tech_doc/erlang_global_20091109.txt 1. 介绍:这 ...

  8. pytest命令行选项

    -m 标记 代码加一个装饰器:@pytest.mark.run_bbc_test,命令行添加 -m run_bbc_test,执行带@pytest.mark.run_bbc_test的测试用例: -k ...

  9. [PYTHON 实作] 算100

    问题:编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性.例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100 ...

  10. PHP中GD库的使用

    1.基本步骤 <?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午9:34 * 熟悉步骤 */ // ...