建第一个注解java
package com.tmser.annotation;spring
/**ide
* *@interface用来声明一个注解,其中的每个方法其实是声明了一个配置参数。 *方法的名称就是参数的名称,返回值类型就是参数的类型。 *能够经过default来声明参数的默认值。 *在这里能够看到@Retention和@Target这样的元注解,用来声明注解自己的行为。 *@Retention用来声明注解的保留策略,有CLASS、RUNTIME和SOURCE这三种, *分别表示注解保存在类文件、JVM运行时刻和源代码中。 *只有当声明为RUNTIME的时候,才可以在运行时刻经过反射API来获取到注解的信息。 *@Target用来声明注解能够被添加在哪些类型的元素上,如类型、方法和域等。 *就能够定义一个注解了,它将自动继承Annotation */
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
//这里定义了一个空的注解,它能干什么呢。我也不知道,但他能用。 }
类,方法,字段使用annotation,能够经过反射获取。post
Class getAnnotation(Class<T> annotationClass)
code
Method getAnnotation(Class<T> annotationClass)
blog
Filed getAnnotation(Class<T> annotationClass)
继承
在spring中能够结合BeanPostProcessor 实现,在 postProcessBeforeInitialization 处理每一个bean的类,方法,字段的annotation。get
BeanPostProcessor简介:it
Spring BeanPostProcesssor一般被称为Spring Bean回调处理器,它通常用于在实例化一个bean的先后增长一些附加操做,它会对全局的Spring bean配置生效。io
示例代码:
@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