Answers for "CustomField Annotation like @Value"

0

CustomField Annotation like @Value

@Component
public class CustomValueBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean == null){
            return bean;
        }
        //Filter out fields marked with custom annotation @ CustomValue
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for(Field declaredField : declaredFields){
            CustomValue annotation = declaredField.getAnnotation(CustomValue.class);
            if(annotation == null){
                continue;
            }
            ReflectionUtils.makeAccessible(declaredField);
            try{
                //Custom parse annotation field to get value
                String value = getValue(annotation);
                //Injects the value into the target field
                declaredField.set(bean, value);
            } catch (Exception e){
                e.printStackTrace();;
            }
        }
        return bean;
    }

    /** Get value by custom */
    private String getValue(CustomValue annotation) {
		return "";
    }
}
Posted by: Guest on August-31-2021

Browse Popular Code Answers by Language