当前位置: 移动技术网 > IT编程>开发语言>Java > 谈谈Java中自定义注解及使用场景

谈谈Java中自定义注解及使用场景

2020年09月07日  | 移动技术网IT编程  | 我要评论
java自定义注解一般使用场景为:自定义注解+拦截器或者aop,使用自定义注解来自己设计框架,使得代码看起来非常优雅。本文将先从自定义注解的基础概念说起,然后开始实战,写小段代码实现自定义注解+拦截器

java自定义注解一般使用场景为:自定义注解+拦截器或者aop,使用自定义注解来自己设计框架,使得代码看起来非常优雅。本文将先从自定义注解的基础概念说起,然后开始实战,写小段代码实现自定义注解+拦截器,自定义注解+aop。

一. 什么是注解(annotation)

java注解是什么,以下是引用自维基百科的内容

java注解又称java标注,是jdk5.0版本开始支持加入源代码的特殊语法元数据。

java语言中的类、方法、变量、参数和包等都可以被标注。和javadoc不同,java标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。java虚拟机可以保留标注内容,在运行时可以获取到标注内容。当然它也支持自定义java标注。

二. 注解体系图

元注解:java.lang.annotation中提供了元注解,可以使用这些注解来定义自己的注解。主要使用的是target和retention注解

注解处理类:既然上面定义了注解,那得有办法拿到我们定义的注解啊。java.lang.reflect.annotationelement接口则提供了该功能。注解的处理是通过java反射来处理的。

如下,反射相关的类class, method, field都实现了annotationelement接口。

因此,只要我们通过反射拿到class, method, field类,就能够通过getannotation(class<t>)拿到我们想要的注解并取值。

三. 常用元注解

target:描述了注解修饰的对象范围,取值在java.lang.annotation.elementtype定义,常用的包括:

  • method:用于描述方法
  • package:用于描述包
  • parameter:用于描述方法变量
  • type:用于描述类、接口或enum类型

retention: 表示注解保留时间长短。取值在java.lang.annotation.retentionpolicy中,取值为:

  • source:在源文件中有效,编译过程中会被忽略
  • class:随源文件一起编译在class文件中,运行时忽略
  • runtime:在运行时有效

只有定义为retentionpolicy.runtime时,我们才能通过注解反射获取到注解。

所以,假设我们要自定义一个注解,它用在字段上,并且可以通过反射获取到,功能是用来描述字段的长度和作用。

@target(elementtype.field) // 注解用于字段上
@retention(retentionpolicy.runtime) // 保留到运行时,可通过注解获取
public @interface myfield {
 string description();
 int length();
}

四. 示例-反射获取注解

先定义一个注解:

@target(elementtype.field)
@retention(retentionpolicy.runtime)
public @interface myfield {
 string description();
 int length();
}

通过反射获取注解

public class myfieldtest {
 //使用我们的自定义注解
 @myfield(description = "用户名", length = 12)
 private string username;

 @test
 public void testmyfield() {
  // 获取类模板
  class c = myfieldtest.class;
  // 获取所有字段
  for (field f : c.getdeclaredfields()) {
   // 判断这个字段是否有myfield注解
   if (f.isannotationpresent(myfield.class)) {
    myfield annotation = f.getannotation(myfield.class);
    system.out.println("字段:[" + f.getname() + "], 描述:[" + annotation.description() + "], 长度:[" + annotation.length() + "]");
   }
  }
 }
}

运行结果

应用场景一:自定义注解+拦截器 实现登录校验

接下来,我们使用springboot拦截器实现这样一个功能,如果方法上加了@loginrequired,则提示用户该接口需要登录才能访问,否则不需要登录。

首先定义一个loginrequired注解

@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface loginrequired {

}

然后写两个简单的接口,访问sourcea,sourceb资源

@restcontroller
public class indexcontroller {
 @getmapping("/sourcea")
 public string sourcea() {
  return "你正在访问sourcea资源";
 }

 @getmapping("/sourceb")
 public string sourceb() {
  return "你正在访问sourceb资源";
 }
}

没添加拦截器之前成功访问

实现spring的handlerinterceptor 类先实现拦截器,但不拦截,只是简单打印日志,如下:

public class sourceaccessinterceptor implements handlerinterceptor {
 @override
 public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
  system.out.println("进入拦截器了");
  return true;
 }

 @override
 public void posthandle(httpservletrequest request, httpservletresponse response, object handler, modelandview modelandview) throws exception {
 }

 @override
 public void aftercompletion(httpservletrequest request, httpservletresponse response, object handler, exception ex) throws exception {
 }
}

实现spring类webmvcconfigurer,创建配置类把拦截器添加到拦截器链中

@configuration
public class interceptortrainconfigurer implements webmvcconfigurer {
 @override
 public void addinterceptors(interceptorregistry registry) {
  registry.addinterceptor(new sourceaccessinterceptor()).addpathpatterns("/**");
 }
}

拦截成功如下

在sourceb方法上添加我们的登录注解@loginrequired

@restcontroller
public class indexcontroller {
 @getmapping("/sourcea")
 public string sourcea() {
  return "你正在访问sourcea资源";
 }

 @loginrequired
 @getmapping("/sourceb")
 public string sourceb() {
  return "你正在访问sourceb资源";
 }
}

简单实现登录拦截逻辑

@override
public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
 system.out.println("进入拦截器了");
 // 反射获取方法上的loginrequred注解
 handlermethod handlermethod = (handlermethod) handler;
 loginrequired loginrequired = handlermethod.getmethod().getannotation(loginrequired.class);
 if (loginrequired == null) {
  return true;
 }
 // 有loginrequired注解说明需要登录,提示用户登录
 response.setcontenttype("application/json; charset=utf-8");
 response.getwriter().print("你访问的资源需要登录");
 return false;
}

运行成功,访问sourceb时需要登录了,访问sourcea则不用登录

应用场景二:自定义注解+aop 实现日志打印

先导入切面需要的依赖包

<dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-aop</artifactid>
</dependency>

定义一个注解@mylog

@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface mylog {

}

定义一个切面类,见如下代码注释理解:

@aspect // 1.表明这是一个切面类
@component
public class mylogaspect {
 // 2. pointcut表示这是一个切点,@annotation表示这个切点切到一个注解上,后面带该注解的全类名
 // 切面最主要的就是切点,所有的故事都围绕切点发生
 // logpointcut()代表切点名称
 @pointcut("@annotation(me.zebin.demo.annotationdemo.aoplog.mylog)")
 public void logpointcut() {};
 // 3. 环绕通知
 @around("logpointcut()")
 public void logaround(proceedingjoinpoint joinpoint) {
  // 获取方法名称
  string methodname = joinpoint.getsignature().getname();
  // 获取入参
  object[] param = joinpoint.getargs();

  stringbuilder sb = new stringbuilder();
  for (object o : param) {
   sb.append(o + "; ");
  }
  system.out.println("进入[" + methodname + "]方法,参数为:" + sb.tostring());
  // 继续执行方法
  try {
   joinpoint.proceed();
  } catch (throwable throwable) {
   throwable.printstacktrace();
  }
  system.out.println(methodname + "方法执行结束");
 }
}

在步骤二中的indexcontroller写一个sourcec进行测试,加上我们的自定义注解:

@mylog
@getmapping("/sourcec/{source_name}")
public string sourcec(@pathvariable("source_name") string sourcename){
 return "你正在访问sourcec资源";
}

启动springboot web项目,输入访问地址

到此这篇关于谈谈java中自定义注解及使用场景的文章就介绍到这了,更多相关java 自定义注解内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网