当前位置: 移动技术网 > IT编程>开发语言>Java > Java注解Annotation与自定义注解详解

Java注解Annotation与自定义注解详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

莲都二手房网,艾条的功效与作用,战地恋歌

一:java注解简介

开发中经常使用到注解,在项目中也偶尔会见到过自定义注解,今天就来探讨一下这个注解是什么鬼,以及注解的应用场景和如何自定义注解。

下面列举开发中常见的注解

@override:用于标识该方法继承自超类, 当父类的方法被删除或修改了,编译器会提示错误信息(我们最经常看到的tostring()方法上总能看到这货)

@deprecated:表示该类或者该方法已经不推荐使用,已经过期了,如果用户还是要使用,会生成编译的警告

@suppresswarnings:用于忽略的编译器警告信息

junit测试:@test

spring的一些注解:@controller、@requestmapping、@requestparam、@responsebody、@service、@component、@repository、@resource、@autowire

java验证的注解:@notnull、@email

下面看一下注解override.java的庐山真面目

@target(elementtype.method)
@retention(retentionpolicy.source)
public @interface override {

}

二:java注解基本知识

1. java注解数据类型

注解是写在.java文件中,使用@interface作为关键字, 所以注解也是java的一种数据类型,从广泛的定义来说,class、interface、enum、annotation都属于class类型。

2. java元注解

在创建注解的时候,需要使用一些注解来描述自己创建的注解,就是写在@interface上面的那些注解,这些注解被称为元注解,如在override中看到的@target、@retention等。下面列出一些元注解

@documented: 用于标记在生成javadoc时是否将注解包含进去,可以看到这个注解和@override一样,注解中空空如也,什么东西都没有

@documented
@retention(retentionpolicy.runtime)
@target(elementtype.annotation_type)
public @interface documented {

}

@target:用于定义注解可以在什么地方使用,默认可以在任何地方使用,也可以指定使用的范围,开发中将注解用在类上(如@controller)、字段上(如@autowire)、方法上(如@requestmapping)、方法的参数上(如@requestparam)等比较常见。

type : 类、接口或enum声明
field: 域(属性)声明
method: 方法声明
parameter: 参数声明
constructor: 构造方法声明
local_variable:局部变量声明
annotation_type:注释类型声明
package: 包声明

target.java

@documented
@retention(retentionpolicy.runtime)
@target(elementtype.annotation_type)
public @interface target {
  /**
   * returns an array of the kinds of elements an annotation type
   * can be applied to.
   * @return an array of the kinds of elements an annotation type
   * can be applied to
   */
  elementtype[] value();
}
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 */
  type_parameter,

  /** use of a type */
  type_use
}

@inherited:允许子类继承父类中的注解,可以通过反射获取到父类的注解

@documented
@retention(retentionpolicy.runtime)
@target(elementtype.annotation_type)
public @interface inherited {

}

@constraint:用于校验属性值是否合法

@documented
@target({elementtype.annotation_type})
@retention(retentionpolicy.runtime)
public @interface constraint {
  class<? extends constraintvalidator<?, ?>>[] validatedby();
}

@retention:注解的声明周期,用于定义注解的存活阶段,可以存活在源码级别、编译级别(字节码级别)、运行时级别

source:源码级别,注解只存在源码中,一般用于和编译器交互,用于检测代码。如@override, @suppresswarings。

class:字节码级别,注解存在于源码和字节码文件中,主要用于编译时生成额外的文件,如xml,java文件等,但运行时无法获得。 如mybatis生成实体和映射文件,这个级别需要添加jvm加载时候的代理(javaagent),使用代理来动态修改字节码文件。

runtime:运行时级别,注解存在于源码、字节码、java虚拟机中,主要用于运行时,可以使用反射获取相关的信息。

@documented
@retention(retentionpolicy.runtime)
@target(elementtype.annotation_type)
public @interface retention {
  /**
   * returns the retention policy.
   * @return the retention policy
   */
  retentionpolicy value();
}

3. java注解的内容

在上面的注解源码中可以看到有的注解中没有任何内容,有的注解的有内容,看似像方法。

注解的内容的语法格式: 数据类型 属性名() default 默认值,数据类型用于描述属性的数据类型,默认值是说当没有给属性赋值时使用默认值,一般string使用空字符串”“作为默认值,数组一般使用空数组{ }作为默认值.

下面看一下springmvc中的requestmapping的注解的声明

@target({elementtype.method, elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@mapping
public @interface requestmapping {
  string name() default "";

  @aliasfor("path")
  string[] value() default {};

  @aliasfor("value")
  string[] path() default {};

  requestmethod[] method() default {};
  string[] params() default {};
  string[] headers() default {};
  string[] consumes() default {};
  string[] produces() default {};
}

使用springmvc中的requestmapping注解

@requestmapping(value = "/list", 
        method = requestmethod.post, 
        produces = {"application/json;charset=utf-8;"})
public string list(){

}

4. 注解的使用场景

可以通过注解的声明周期来分析注解的使用场景:

source源码级别:给编译器使用,如@override、@deprecated 等, 这部分开发者应该使用的场景不多

class:字节码级别,这部分也很少见到

runtime:运行时级别,这个是最多的,几乎开发者使用到的注解都是运行时级别,运行时注解常用的有以下几种情况

注解中没有任何属性的,空的注解,这部分注解通常起到一个标注的作用,如@test、@before、@after,通过获取这些标记注解在逻辑上做一些特殊的处理

可以使用约束注解@constraint来对属性值进行校验,如@email, @notnull等

可以通过在注解中使用属性来配置一些参数,然后可以使用反射获取这些参数,这些注解没有其他特殊的功能,只是简单的代替xml配置的方式来配置一些参数。使用注解来配置参数这在spring boot中得到了热捧,如@configuration

关于配置方式xml vs annotation, 一般使用xml配置一些和业务关系不太紧密的配置,使用注解配置一些和业务密切相关的参数。

三:java注解和反射基本api

// 获取某个类型的注解
public <a extends annotation> a getannotation(class<a> annotationclass);
// 获取所有注解(包括父类中被inherited修饰的注解)
public annotation[] getannotations(); 
// 获取声明的注解(但是不包括父类中被inherited修饰的注解)
public annotation[] getdeclaredannotations();
// 判断某个对象上是否被某个注解进行标注
public boolean isannotationpresent(class<? extends annotation> annotationclass)

// 获取某个类声明的所有字段
public field[] getdeclaredfields() throws securityexception;
// 获取某个方法
public method getmethod(string name, class<?>... parametertypes);

四:自定义注解

使用自定义注解+拦截器或者是aop等可以进行权限的控制。

下面通过定义一个注解用来限制当用户访问接口时必须要登录的示例

步骤一:定义注解

requireslogin.java

@documented
@target({elementtype.method})
@retention(retentionpolicy.runtime)
public @interface requireslogin {

}

步骤二:使用注解

@controller
@requestmapping("/user")
public class usercontroller {
  @requireslogin
  @requestmapping(value = "/list", produces = {"application/json;charset=utf-8;"})
  public string getuserlist(){

    system.out.println("--------------");
    return "[{'id': 1, 'username':'zhangsan'}]";
  }
}

步骤三:使用aop进行拦截,解析注解

public class loginadvices {
  public void before(joinpoint joinpoint) throws exception{

    object target = joinpoint.gettarget();
    string methodname = joinpoint.getsignature().getname();

    system.out.println(target + "-------" + methodname);
    method method = target.getclass().getmethod(methodname);
    boolean annotationpresent = method.isannotationpresent(requireslogin.class);
    if (annotationpresent) {
      // 用户必须登录
      boolean islogin = false;
      if (!islogin) {
        throw new exception("访问该接口必须先登录");
      } else {
        system.out.println("已登录...");
      }
    }
  }
}

在applicationcontext.xml中配置aop

<bean id="loginadvices" class="com.mengdee.manager.aop.loginadvices"/>
  <!-- aop配置 -->
  <aop:config proxy-target-class="true">
    <!--切面 -->
    <aop:aspect ref="loginadvices">
      <!-- 切点 -->
      <aop:pointcut id="pointcut1" expression="execution(* com.mengdee.manager.controller.*.*(..))"/>
      <!--连接通知方法与切点 -->
      <aop:before method="before" pointcut-ref="pointcut1"/>
    </aop:aspect>
  </aop:config>

自定义异常

为什么要自定义异常

java虽然提供了丰富的异常处理类,但是在项目中还会经常使用自定义异常,其主要原因是java提供的异常类在某些情况下还是不能满足各种业务的需求。 例如系统中有些错误是符合java语法,但不符合业务逻辑。如当用户登录时账号不存在或者账号已锁定可以自定义一个账号异常accountexception。

或者有些情况下java的同一个异常可能会有多种原因引起,在排查问题时不容易定位错误,此时可以使用自定义一个更加明确的异常。

自定义异常的好处:自定义异常可以使异常更加明确,可以隐藏底层的异常,这样更安全,异常信息更加直观。

自定义异常的使用:自定义异常一般继承自exception或者runtimeexception,根据业务需要可以带一些属性作为构造函数的参数,自定义异常需要程序员手动抛出异常,并处理异常。

下面是apache shiro中自定义异常的示例

public class shiroexception extends runtimeexception {
  public shiroexception() {
  }

  public shiroexception(string message) {
    super(message);
  }

  public shiroexception(throwable cause) {
    super(cause);
  }

  public shiroexception(string message, throwable cause) {
    super(message, cause);
  }
}

以上即是关于java注解annotation与自定义注解的详细说明

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网