目的:

  1.Java注解简介

  2.Java元注解(重点)

  3.自定义注解

      案例一(获取类与方法上的注解值)

      案例二(获取类属性上的注解属性值)

      案例三(获取参数修饰注解对应的属性值)

4.Aop自定义注解的应用(重点)


Java注解简介

1. Java注解(Annotation)

Java注解是附加在代码中的一些元信息,用于一些工具在编译、

运行时进行解析和使用,起到说明、配置的功能。

注解相关类都包含在java.lang.annotation包中。

2. Java注解分类

2.1 JDK基本注解

2.2 JDK元注解

2.3 自定义注解

3. JDK基本注解

3.1 @Override

重写

3.2 @Deprecated

已过时

3.3 @SuppressWarnings(value = "unchecked")

压制编辑器警告


Java元注解

  作用:元注解用于修饰其他的注解

  • @Retention:定义注解的保留策略
    @Retention(RetentionPolicy.SOURCE)             //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) //注解会在class字节码文件中存在,在运行时可以通过反射获取到
  • @Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)

      @Target(ElementType.TYPE)                      //接口、类
@Target(ElementType.FIELD) //属性
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE) //局部变量
@Target(ElementType.ANNOTATION_TYPE) //注解
@Target(ElementType.PACKAGE) //包

注:可以指定多个位置,例如:

@Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用

  • @Inherited:指定被修饰的Annotation将具有继承性
@Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.

自定义注解

注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):

标记Annotation:

没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息

元数据Annotation:

包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;

如何自定义注解?

使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:

Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,

而且我们还可以使用default关键字为这个成员变量设定默认值;

注意:只有名字为“value”属性,赋值时可以省略属性名

案例一(获取类与方法上的注解值):

  TranscationModel

package com.huangting.annotation.P1;
/**
* enum枚举
*/
public enum TranscationModel {
Read, ReadWrite, Write
}

  MyAnnotation1

package com.huangting.annotation.P1;

import java.lang.annotation.*;

/**
* MyAnnotation1注解可以用在类、接口、属性、方法上
* 注解运行期也保留
* 不可继承
*/
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
String name();
}

  MyAnnotation2

package com.huangting.annotation.P1;

import java.lang.annotation.*;

/**
* MyAnnotation2注解可以用在方法上
* 注解运行期也保留
* 不可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
TranscationModel model() default TranscationModel.ReadWrite;
}

MyAnnotation3

package com.huangting.annotation.P1;

import java.lang.annotation.*;

/**
* MyAnnotation3注解可以用在方法上
* 注解运行期也保留
* 可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
TranscationModel[] models() default TranscationModel.ReadWrite;
}

Dome1

package com.huangting.annotation.P1;

/**
* 获取类与方法上的注解值
*/
@MyAnnotation1(name = "abc")
public class Demo1 { @MyAnnotation1(name = "xyz")
private Integer age; @MyAnnotation2(model = TranscationModel.Read)
public void list() {
System.out.println("list");
} @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
public void edit() {
System.out.println("edit");
}
}

Demo1Test

package com.huangting.annotation.P1;
import org.junit.Test;
public class Demo1Test {
@Test
public void list() throws Exception {
// 获取类上的注解
MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class);
System.out.println(annotation1.name());//abc // 获取方法上的注解
MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class);
System.out.println(myAnnotation2.model());//Read
} @Test
public void edit() throws Exception {
MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);
for (TranscationModel model : myAnnotation3.models()) {
System.out.println(model);//Read,Write
}
}
}

效果:

注意:

jar包的运用中最好不要出现test,把《scope》《/scope》删除即可

否则会报错@Test无法使用

案例二(获取类属性上的注解属性值)

TestAnnotation

package com.huangting.annotation.P2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; //@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
String value() default "默认value值";
String what() default "这里是默认的what属性对应的值";
}

Dome2

package com.huangting.annotation.P2;

/**
* 获取类属性上的注解属性值
*/
public class Demo2 {
@TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
private static String msg1; @TestAnnotation("这就是value对应的值1")
private static String msg2; @TestAnnotation(value = "这就是value对应的值2")
private static String msg3; @TestAnnotation(what = "这就是what对应的值")
private static String msg4;
}
Demo2Test 
package com.huangting.annotation.P2;

import org.junit.Test;

public class Demo2Test {
@Test
public void test1() throws Exception {
TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
System.out.println(msg1.value());
System.out.println(msg1.what());
} @Test
public void test2() throws Exception{
TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
System.out.println(msg2.value());
System.out.println(msg2.what());
} @Test
public void test3() throws Exception{
TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
System.out.println(msg3.value());
System.out.println(msg3.what());
} @Test
public void test4() throws Exception{
TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
System.out.println(msg4.value());
System.out.println(msg4.what());
}
}

效果:

案例三(获取参数修饰注解对应的属性值):

IsNotNull 
package com.huangting.annotation.P3;

import java.lang.annotation.*;

/**
* 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
*/
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
boolean value() default false;
}
Demo3 
package com.huangting.annotation.P3;

/**
* 获取参数修饰注解对应的属性值
*/
public class Demo3 { public void hello1(@IsNotNull(true) String name) {
System.out.println("hello:" + name);
} public void hello2(@IsNotNull String name) {
System.out.println("hello:" + name);
}
}
Demo3Test 
package com.huangting.annotation.P3;
import org.junit.Test;
import java.lang.reflect.Parameter;
public class Demo3Test { @Test
public void hello1() throws Exception {
Demo3 demo3 = new Demo3();
for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
if(annotation != null){
System.out.println(annotation.value());//true
}
}
} @Test
public void hello2() throws Exception {
Demo3 demo3 = new Demo3();
for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
if(annotation != null){
System.out.println(annotation.value());//false
}
}
}
}

效果:


Aop自定义注解的应用

  MyLog 

package com.huangting.annotation.Aop;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
String desc();
}
MyLogAspect 
package com.huangting.annotation.Aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; @Component
@Aspect
public class MyLogAspect {
private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class); /**
* 只要用到了com.huangting.annotation.Aop.MyLog这个注解的,就是目标类
*/
@Pointcut("@annotation(com.huangting.annotation.Aop.MyLog)")
private void MyValid() {
} @Before("MyValid()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
System.out.println("[" + signature.getName() + " : start.....]");
System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());
}
}
BaseTestCase 
package com.huangting.annotation.Aop;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class BaseTestCase { }
LogController 
package com.huangting.annotation.Aop;

import org.springframework.stereotype.Component;

@Component
public class LogController { @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
public void testLogAspect(){
System.out.println("墙头马上遥相顾");
}
}
LogControllerTest 
package com.huangting.annotation.Aop;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; public class LogControllerTest extends BaseTestCase {
@Autowired
private LogController logController; @Test
public void testLogAspect(){
logController.testLogAspect();
}
}

效果:

谢谢观看!

java之aop使用及自定义注解的更多相关文章

  1. AOP中获取自定义注解的参数值

      目录 一.利用注解实现AOP的基本流程 1.1.创建一个注解,用来注解切点(pointcut) 1.2.创建一个service,使用上面定义的注解来指定切点 1.3.创建Aspect,增加业务逻辑 ...

  2. [Java]利用拦截器和自定义注解做登录以及权限验证

    1.自定义注解 需要验证登录的注解 package com.etaofinance.wap.common; import java.lang.annotation.Documented; import ...

  3. 利用Spring AOP自定义注解解决日志和签名校验

    转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先 ...

  4. (转)利用Spring AOP自定义注解解决日志和签名校验

    一.需解决的问题 部分API有签名参数(signature),Passport首先对签名进行校验,校验通过才会执行实现方法. 第一种实现方式(Origin):在需要签名校验的接口里写校验的代码,例如: ...

  5. Spring Boot系列——AOP配自定义注解的最佳实践

    AOP(Aspect Oriented Programming),即面向切面编程,是Spring框架的大杀器之一. 首先,我声明下,我不是来系统介绍什么是AOP,更不是照本宣科讲解什么是连接点.切面. ...

  6. aop 拦截含有特定注解的类

    1.功能点:使用aop拦截含有自定义注解的类 1.自定义注解 package com.zhuanche.common.dingdingsync; import java.lang.annotation ...

  7. 服务限流 -- 自定义注解基于RateLimiter实现接口限流

    1. 令牌桶限流算法 令牌桶会以一个恒定的速率向固定容量大小桶中放入令牌,当有浏览来时取走一个或者多个令牌,当发生高并发情况下拿到令牌的执行业务逻辑,没有获取到令牌的就会丢弃获取服务降级处理,提示一个 ...

  8. 170313、poi:采用自定义注解的方式导入、导出excel(这种方式比较好扩展)

    步骤一.自定义注解 步骤二.写Excel泛型工具类 步骤三.在需要导出excel的类属相上加上自定义注解,并设置 步骤四.写service,controller 步骤一:自定义注解 import ja ...

  9. Spring实现自定义注解并且配置拦截器进行拦截

    有时候我们会自定义注解,并且需要配置拦截器对请求方法含有该自定义注解的方法进行拦截操作 自定义注解类 NeedToken.java import java.lang.annotation.Docume ...

随机推荐

  1. HTTP Referrer和Referrer Policy 设置

    referrer是HTTP请求header的报文头,用于指明当前流量的来源参考页面.通过这个信息,我们可以知道访客是怎么来到当前页面的.这对于Web Analytics非常重要,可以用于分析不同渠道流 ...

  2. 苹果IPhone真机开发调试

    需要 在苹果开发网站 加入真机的UDID, 并在Profile中勾选该手机

  3. 百度编辑器contentChange监听不到图片上传

    将ueditor组件化到java项目中,当调用组件后,绑定函数,监听contentchange如下图: um.addListener("contentChange",functio ...

  4. qemu通过控制台向虚拟机输入组合键

    ctrl+alt+2 开启控制台 ctrl+alt+1 关闭控制台 在控制台中输入 sendkey ctrl-alt-delete 发送指令

  5. MiniDao & Freemarker & include

    minidao include - 国内版 Binghttps://cn.bing.com/search?q=minidao+include&qs=n&form=QBRE&sp ...

  6. Nessus更新到8.5.0

    Nessus更新到8.5.0   此次更新,主要涉及以下变化: (1)Nessus的用户注册和激活流程进行简化.用户可以在Nessus软件中直接进行注册和激活. (2)Nessus报告生成功能得到加强 ...

  7. for(auto i : v)遍历容器元素

    c++11的新特性,v是一个可遍历的容器或流,比如vector类型,i就用来在遍历过程中获得容器里的每一个元素. for(auto i:v) for(auto &i:v) 代码1:#inclu ...

  8. Postgresql常用函数整理

    一.字符串函数 1.函数:string || string(string || non-string) 说明:字符串(或与非字符串)连接 示例: 2.函数:char_length(string) 说明 ...

  9. VMware 快速克隆出多个 Linux centos7 环境

    这样一台系统就已经克隆好了,但是,现在还没有完,因为是克隆的,里面的ip地址和创建的主机名都是一样,需要进行修改 登录服务器,然后使用 [ifcfg-ens33需根据实际情况而定] vi /etc/s ...

  10. 【432】COMP9024,Exercise9

    eulerianCycle.c What determines whether a graph is Eulerian or not? Write a C program that reads a g ...