Changing bean properties programmatically
Hi all
I'm using this environment:
I'ld like to valorize some bean properties by quirying the DB. For example let's image this code:
Code:
import stuffs....
@Service("mySimpleSvc")
public class MySvc{
@MyCustomAnnotation
protected String valorizeFromDb;
protected String notValorizeFromDb;
}
What I would like is to te able in valorizing the property valorizeFromDb after bean creation and by querying the database
In order to do it i was thinking to use a "BeanFactoryPostProcessor" way but in this case I can't autowire spring beans.
I was thinking in something like this:
Code:
@Service("valorizeFromDbSvc")
public class ConfigurationService implements BeanFactoryPostProcessor {
private MyDao myDao;
@Autowired
public void setParamCfgMgrDao(MyDao dao){
this.myDao = dao;
}
private void checkObjectFields(MyInterface object) throws IllegalArgumentException, IllegalAccessException, MktiDbException, InvocationTargetException{
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if(field.isAnnotationPresent(MyCustomAnnotation.class)){
if (field.isAnnotationPresent(MyCustomAnnotation.class)) {
MyCustomAnnotation annotation = field.getAnnotation(MyCustomAnnotation.class);
Object value = getNotNullParamConfiguration(field.getName(), field.getType(), annotation);
//This is commons beans BeanUtils class
BeanUtils.setProperty(object, field.getName(), value);
}
}
}
}
@SuppressWarnings("unchecked")
protected <T> T getNotNullParamConfiguration(String paramName, Class<T> returnType, MyCustomAnnotation annotation) throws MktiDbException {
T result = null;
if (paramName != null && !paramName.isEmpty()) {
String value = myDao.getValueConfiguration(paramName);
try {
if (Number.class.isAssignableFrom(returnType)) {
result = (T) NumberUtils.parseNumber(value.trim(), (Class<Number>) returnType);
} else {
return (T) value;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory clbf) throws BeansException {
try{
Map<String, MyInterface> beans = clbf.getBeansOfType(MyInterface.class);
if(beans != null && !beans.isEmpty()){
Collection<MyInterface> valori = beans.values();
for (IInViMallMktIntelligence bean : valori) {
checkObjectFields(bean);
}
}
} catch (Exception e) {
String message = "Error; error message: "+e.getMessage();
logger.fatal(message, e);
throw new IllegalStateException(message);
}
}
}
But in this case, obviously, i can't autowire the DAO object.
Is there any other way in order to do it?
Thank you
Angelo