java annotation demo

[code="java"][/code]package com.woyo.reader.cms.remote.service;

import java.lang.reflect.Field;

import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import com.woyoframework.modules.spring.exetend.PropertyConfig;

@Service
public class Processor extends InstantiationAwareBeanPostProcessorAdapter{
public boolean postProcessAfterInstantiation(Object bean, String beanName){
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
RequestFor p =field.getAnnotation(RequestFor.class);
if(p!=null){
String value = p.value();
if(!value.isEmpty()){
System.out.print(value);
}else{
System.out.print("date=="+p.date());
}
}
}
});
return true;
}


}


demo2:
package com.woyoframework.modules.spring.exetend;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import org.springframework.beans.BeansException;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

@Service
public class ConfigAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
@Autowired
private ExtendedPropertyPlaceholderConfigurer propertyConfigurer;

private SimpleTypeConverter typeConverter = new SimpleTypeConverter();

/**
* <p>通过config配置变量,bean初始化以后设置properties文件里面的值</p>
* {@inheritDoc}
*/
@Override
public boolean postProcessAfterInstantiation(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
PropertyConfig cfg = field.getAnnotation(PropertyConfig.class);
if (cfg != null) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@PropertyConfig annotation is not supported on static fields");
}

String key = cfg.value().length() <= 0 ? field.getName() : cfg.value();
Object value = propertyConfigurer.getProperty(key);
if (cfg.required() && value == null) {
throw new NullPointerException(bean.getClass().getSimpleName() + "." + field.getName()
+ "is requred,but not been configured");
} else if (value != null) {
Object _value = typeConverter.convertIfNecessary(value, field.getType());
ReflectionUtils.makeAccessible(field);
field.set(bean, _value);
}
}
}
});

return true;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值