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 ...
随机推荐
- Centos 6.3 Realtek Audio Driver Compile
/**************************************************************************** * Centos 6.3 Realtek A ...
- [转载] ffmpeg摄像头视频采集-采集步骤概述并采集一帧视频
近期由于工作任务,需要开发一个跨平台视频聊天系统,其中就用到了ffmpeg进行采集与编码,网上找了一大堆的资料,虽然都有一些有用的东西,但实在太碎片化了,这几天一直在整理和实验这些资料,边整理,边做一 ...
- 深入理解vsto,开发word插件的利器
开发了vsto,客户那边也有一些反映插件安装失败或者加载不上的情况.于是我下定决定再理解下vsto的工作机制,如下图: 如上图所示,我把vsto的解决方案分为两部分,一部分是vsto Add-ins, ...
- 剑指offer-第六章面试中的各项能力(翻转单词的顺序VS左旋转字符串)
//题目1:翻转单词顺序例如“Hello world!”翻转后为world! Hello. //思路:首先翻转整个字符串,然后再分别翻转每个单词. //题目2:左旋转字符串,是将字符串的前面几个(n) ...
- UVA11168 Airport
题意 PDF 分析 首先发现距离最短的直线肯定在凸包上面. 然后考虑直线一般方程\(Ax+By+C=0\),点\((x_0,y_0)\)到该直线的距离为 \[ \frac{|Ax_0+By_0+C|} ...
- Tornado输出和响应头
1.输出 再来看看输出`write`,实际上,`write`并没有直接把数据返回给前端,而是先写到缓存区,函数结束之后才会返回到前端,我们验证如下 class FlushHandler(tornado ...
- 关于AutoCommit
AutoCommit设置为true(大多数JDBCdrive的默认配置),则每次执行的SQL语句执行完成后都会落实到数据库中:如果想要在跨语句事务,则需要添加Begin Transiction,Com ...
- 【Python学习笔记】输出现在的时间
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) 2016-01-27 21:40:25
- 获取设备 ID 和名称
获取设备 ID 和名称 .NET Framework 3.5 其他版本 更新:2007 年 11 月 要获取设备的名称,请使用 Dns.GetHostName 属性.通常情况下,默认名称为“P ...
- Java-Maven-Runoob:Maven 项目文档
ylbtech-Java-Maven-Runoob:Maven 项目文档 1.返回顶部 1. Maven 项目文档 本章节我们主要学习如何创建 Maven 项目文档. 比如我们在 C:/MVN 目录下 ...