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. 【MFC】MoveWindow();函数使用详解

    摘自:http://blog.csdn.net/yjkwf/article/details/5281207 CWnd::MoveWindow 详解 2010-02-02 16:08 3432人阅读 评 ...

  2. windows 下后台启动 redis

    1. 进入 DOS窗口 2. 在进入Redis的安装目录 3. 输入:redis-server --service-install redis.windows.conf --loglevel verb ...

  3. 基功太差,怨不得天,得下苦功——WAP面试,正式招聘号角响起

    WAP面试,直接考察coding能力. 面试官是一个日本先生.人超级Nice.一直朝我微笑. 简短的self-introdution后,就让写代码了. (欧巴桑昨天面的,回去后就把题目告诉我们了,我昨 ...

  4. 5款实用的硬盘、SSD固态硬盘、U盘、储存卡磁盘性能测试工具绿色版

    http://www.iplaysoft.com/disk-benchmark-tools.html/comment-page-1#comment-149425

  5. NET Core中使用MediatR实现命令和中介者模式

    NET Core中使用MediatR实现命令和中介者模式 https://www.cnblogs.com/yilezhu/p/9866068.html 在本文中,我将解释命令模式,以及如何利用基于命令 ...

  6. vue 相邻自定义组件渲染错误正确的打开方式

    话不多说看问题: 当封装自定义组件时例如(自定义下拉列表)两个相同的组件在多次v-if变化时偶尔会发生渲染错误,明明赋值正确但是组建中的ajax方法可能返回的数据乱掉,或者其他神逻辑错误. 经过查询发 ...

  7. QLCDNumber设置背景色和显示数字颜色【转载】

    http://www.qtcn.org/bbs/read-htm-tid-55176.html //LCD时间显示    QLCDNumber *m_pLcdTime = new QLCDNumber ...

  8. mybatis排序

    排序的时候#和$的分别 1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号.如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by ...

  9. C语言中的printf函数的输入输出问题

    这个问题是个很基础,但是我一直不知道的问题,是同学问了之后才知道的,长知识了. 这里要注意的是,printf函数是从右向左计算,从左向右输出. 距离如下: #include <stdio.h&g ...

  10. java md5 函数

    private static final String md5(final String s) { final String MD5 = "MD5"; try { // Creat ...