java怎么如何使用@Annotation注解

发布时间:2021-06-09 18:10:53 作者:Leah
来源:亿速云 阅读:133

今天就跟大家聊聊有关java怎么如何使用@Annotation注解,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、 注解定义方式

直接上代码,看看spring中@Service注解的定义就知道了:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

 String value() default "";
 
}

可以看到注解的定义和接口定义很像,但是多了@字符,注解的定义上有以下约定:

二、元注解

所谓元注解就是java中默认实现的专门对注解进行注解的注解。元注解的总数就5个,下面我们以上面讲到的@Service注解为例子各个击破:

1.@Target

此注解用于表示当前注解的使用范围,@Target({ElementType.TYPE})就代表着@Service这个注解是专门用来注解到类、接口、或者枚举类型上面的,当在方法上面加这个注解时,就会报错。可以看到注解位置是一个枚举类型,完整定义如下

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
}

2.@Retention

此注解用于表示当前注解的生命周期,说人话就是这个注解作用会保留到什么时候,如@Retention(RetentionPolicy.RUNTIME)就表示在程序运行期间依然有效,此时就可以通过反射拿到注解的信息,完整的枚举定义如下

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
}

3.@Documented

当被此注解所注解时,使用javadoc工具生成文档就会带有注解信息。

4.@Inherited

此注解与继承有关,当A注解添加此注解后,将A注解添加到某类上,此类的子类就会继承A注解。

@Inherited
public @interface A{
}

@A
public class Parent{}

public class Son entends Parant{}//Son类继承了父类的A注解

5.@Repeatable

此注解顾名思义是拥有可以重复注解的能力。想象这样一个场景,我们需要定时执行某个任务,需要在每周一和周三执行,并且这个时间是可以灵活调整的,此时这个元注解就能派上用场:

@Repeatable(Schedules.class)
public @interface Schedule {
  String date();
}

public @interface Schedules {
  Schedule[] value();
}

@Schedule(date = "周一")
@Schedule(date = "周三")
public class Executor {
}

注意看到此元注解后面括号里内容,在这指定的类叫做容器注解,意思是保存这多个注解的容器,故我们创建一个@Schedules注解作为@Schedule的容器注解,容器注解必须含有一个名字为value,返回类型为需放入此容器的注解数组的属性。

三、自定义实现一个注解

下面我们以web项目中非常常见的鉴权场景为例自己实现一个自定义注解。

首先我们定义系统的使用人员身份,有超级管理员、管理员、访客三种身份。

public enum IdentityEnums {

  SUPER_ADMIN,
  ADMIN,
  VISIVOR

}

接下来我们定义一个权限注解:

@Target({ElementType.TYPE,ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorization {

  IdentityEnums[] value();
  
}

然后使用拦截器的方式,对所有页面进行统一的鉴权管理,此处只展示一些关键代码:

public class AuthInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    if (handler instanceof HandlerMethod)
    {
      IdentityEnums user = getIdentityFromRequset(request);//这里从request里获取账号信息并判断身份,自己实现
      Authorization auth =((HandlerMethod) handler).getMethodAnnotation(Authorization.class);//获取方法上面的注解
      if (!Arrays.asList(auth.value()).contains(user)){
        return false;
      }
    }
    return true;
  }
}

最后在spring配置文件中对拦截器进行配置开启拦截器:

<!-- 拦截器 -->
 <mvc:interceptors>
 <mvc:interceptor>
  <!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->
  <mvc:mapping path="/**" />
  <!-- 拦截器类 -->
  <bean
  class="com.xx.xx.AuthInterceptor"></bean>
 </mvc:interceptor>
 </mvc:interceptors>

在实际使用中,我们将在方法上面添加此自定义注解,当身份权限符合时,才能对页面进行访问,使用方式如下:
@ResponseBody

@RequestMapping(value = "/management")
@Authorization({IdentityEnums.ADMIN,IdentityEnums.SUPER_ADMIN})
public String management(HttpServletRequest request, HttpServletResponse response)
{
  log.info("has permission!");
}

看完上述内容,你们对java怎么如何使用@Annotation注解有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. Java注解(Annotation):请不要小看我!
  2. Annotation注解及元注解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java @annotation

上一篇:mybatis中怎么实现输入映射和输出映射

下一篇:JAVA中怎么使用 Future类

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》