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

  • 相关阅读:
    检索 COM 类工厂中 CLSID 为 {0002450000000000C000000000000046} 的组件时失败,原因是出现以下错误: 80070005。
    行列转换(sqlserver2005 的新方法)
    今天开始要详细的记录学习sharepoint 的进度和相关的一些资料
    SQL SERVER 2005 数据库状态为“可疑”的解决方法
    弹出窗口window.open()的参数列表
    C#术语&&C#关键字
    把一个 ASP.NET 程序转换为了 Web Services
    修饰符(C# 参考)
    C# 中的常用正则表达式
    1、String.format()与String.valueOf()区别 && 2、string.split()
  • 原文地址:https://www.cnblogs.com/treehesoft/p/7211532.html
Copyright © 2011-2022 走看看