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

posted @ 2017-07-20 15:41  大树程序员  阅读(200)  评论(0编辑  收藏  举报