zoukankan      html  css  js  c++  java
  • spring annotation

    建第一个注解

    package com.tmser.annotation;

       /**

     *
     *@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。
     *方法的名称就是参数的名称,返回值类型就是参数的类型。
     *可以通过default来声明参数的默认值。
     *在这里可以看到@Retention和@Target这样的元注解,用来声明注解本身的行为。
     *@Retention用来声明注解的保留策略,有CLASS、RUNTIME和SOURCE这三种,
     *分别表示注解保存在类文件、JVM运行时刻和源代码中。
     *只有当声明为RUNTIME的时候,才能够在运行时刻通过反射API来获取到注解的信息。
     *@Target用来声明注解可以被添加在哪些类型的元素上,如类型、方法和域等。
     *就可以定义一个注解了,它将自动继承Annotation
     */

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {
    //这里定义了一个空的注解,它能干什么呢。我也不知道,但他能用。
    }

    类,方法,字段使用annotation,可以通过反射获取。

    Class getAnnotation(Class<T> annotationClass)

    Method getAnnotation(Class<T> annotationClass)

    Filed  getAnnotation(Class<T> annotationClass)

    在spring中可以结合BeanPostProcessor 实现,在 postProcessBeforeInitialization  处理每个bean的类,方法,字段的annotation。

    BeanPostProcessor简介:

          Spring BeanPostProcesssor通常被称为Spring Bean回调处理器,它一般用于在实例化一个bean的前后增加一些附加操作,它会对全局的Spring bean配置生效。

    示例代码:

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      //TODO 过滤一些不需要检查的bean

      Class<?> beanClass = AopUtils.getTargetClass(bean);
      Field[] beanFields = beanClass.getDeclaredFields();
      for (Field beanField : beanFields) {
        if (!beanField.isAnnotationPresent(TestAnnotation.class)) {
          continue;
        }

        TestAnnotation testAnnotation = beanField.getAnnotation(LOSClient.class);
        //TODO 处理annotation

        ReflectionUtils.makeAccessible(beanField);
        try {
          //设置属性
          beanField.set(bean, getBeanFieldInstance(beanField));
        }
        catch (Exception exception) {
          //TODO
        }
       }
      return bean;
    }

    参考:http://www.tmser.com/?post=34&page=4

  • 相关阅读:
    WPF 模拟UI 键盘录入
    rabbitmq使用dead letter机制来进行retry
    工厂设计模式
    python 内置速度最快算法(堆排)
    简单工厂设计模式
    杂类
    MorkDown 常用语法总结
    使用python列表推导式进行99乘法表
    linux 命令free -m 命令结果分析
    理解记忆三种常见字符编码:ASCII, Unicode,UTF-8
  • 原文地址:https://www.cnblogs.com/treehesoft/p/7211532.html
Copyright © 2011-2022 走看看