#自定义注解仿spring @value
自定义注解类并申明应用在属性上
@Target({java.lang.annotation.ElementType.FIELD}) //声明应用在属性上
@Retention(RetentionPolicy.RUNTIME) //运行期生效
@Documented //Java Doc
@Component
public @interface LogField
{
String v();
}
实现BeanPostProcessor 接口
@Component
public class MyLogFieldBeanPostProcessor implements
BeanPostProcessor {
public MyLogFieldBeanPostProcessor() {
super();
}
@Override
public Object postProcessAfterInitialization(Object bean, String arg1)
throws BeansException {
try {
Object object = AopTargetUtils.getTarget(bean);
Field[] declaredFields = object.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
LogField annotation = declaredField.getAnnotation(LogField.class);
if (null == annotation) {
continue;
}
declaredField.setAccessible(true);
try {
declaredField.set(object, annotation.v());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} catch (Exception e1) { e1.printStackTrace(); }
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String arg1)
throws BeansException {
return bean;
} }
自定义标签的使用 用注解标记value后将v=111赋值给value