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. Hoeffding inequality

    Hoeffding公式为 \epsilon]\leq{2e^{-2\epsilon^2N}}"> 如果把Training error和Test error分别看成和的话,Hoeffdi ...

  2. CodeForces - 963D:Frequency of String (bitset暴力搞)

    You are given a string ss. You should answer nn queries. The ii-th query consists of integer kiki an ...

  3. RabbitMQ学习系列四-EasyNetQ文档跟进式学习与实践

    EasyNetQ文档跟进式学习与实践 https://www.cnblogs.com/DjlNet/p/7603554.html 这里可能有人要问了,为什么不使用官方的nuget包呐:RabbitMQ ...

  4. 理解javascript中的with关键字

    说起js中的with关键字,很多小伙伴们的第一印象可能就是with关键字的作用在于改变作用域,然后最关键的一点是不推荐使用with关键字.听到不推荐with关键字后,我们很多人都会忽略掉with关键字 ...

  5. mysql存入GBK编码字段信息

    set @moneyStr=BASE64_ENCODE(CONVERT(CONCAT('线上报名且已交费',money,'元') using GBK));

  6. 在TreeView 控件上,如果双击任何一个节点的checkbox 只会收到一次After_Check事件 但是check属性变化两次(从false到true 再从true到false),请问该如何解决,谢谢!

    在TreeView 控件上,如果双击任何一个节点的checkbox 只会收到一次After_Check事件 但是check属性变化两次(从false到true 再从true到false),请问该如何解 ...

  7. yum安装报错“rpmts_HdrFromFdno: Header V3 DSA signature: NOKEY, key ID 1e5e0159”

    Do not forget to set gpgkey when installing the oracle-validated rpm Read more: http://oracletoday.b ...

  8. .net中webconfig自定义配置

    在configuration节点,也就是文件的根节点下,增加如下节点 <appSettings> <!--<add key="propPath" value ...

  9. win7 网站发布备注

    1.更改 .NET Framework 版本(改原设置v2.0 为v4.0) 2.程序池设置 3.基本设置 4.Web.config (debug="false") <sys ...

  10. atorg.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:557)

    错误原因: 你当前开发环境中{Hadoop_HOME}\bin\hadoop.dll 文件和你当前的hadoop版本不匹配.  解决方案: 网络下载相应版本的hadoop.dll,并将该文件放入c:\ ...