且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绑定spring mvc命令对象时如何将多个参数名称映射到POJO

更新时间:2023-09-01 15:05:46

来自张杰的建议 like ExtendedBeanInfo

所以我是这样做的

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Alias {
    String[] value();
}

public class AliasedBeanInfoFactory implements BeanInfoFactory, Ordered {
    @Override
    public BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException {
        return supports(beanClass) ? new AliasedBeanInfo(Introspector.getBeanInfo(beanClass)) : null;
    }

    private boolean supports(Class<?> beanClass) {
        Class<?> targetClass = beanClass;
        do {
            Field[] fields = targetClass.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Alias.class)) {
                    return true;
                }
            }
            targetClass = targetClass.getSuperclass();

        } while (targetClass != null && targetClass != Object.class);

        return false;
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 100;
    }
}

public class AliasedBeanInfo implements BeanInfo {
    private static final Logger LOGGER = LoggerFactory.getLogger(AliasedBeanInfo.class);

    private final BeanInfo delegate;

    private final Set<PropertyDescriptor> propertyDescriptors = new TreeSet<>(new PropertyDescriptorComparator());

    AliasedBeanInfo(BeanInfo delegate) {
        this.delegate = delegate;
        this.propertyDescriptors.addAll(Arrays.asList(delegate.getPropertyDescriptors()));

        Class<?> beanClass = delegate.getBeanDescriptor().getBeanClass();
        for (Field field : findAliasedFields(beanClass)) {
            Optional<PropertyDescriptor> optional = findExistingPropertyDescriptor(field.getName(), field.getType());
            if (!optional.isPresent()) {
                LOGGER.warn("there is no PropertyDescriptor for field[{}]", field);
                continue;
            }
            Alias alias = field.getAnnotation(Alias.class);
            addAliasPropertyDescriptor(alias.value(), optional.get());
        }
    }

    private List<Field> findAliasedFields(Class<?> beanClass) {
        List<Field> fields = new ArrayList<>();
        ReflectionUtils.doWithFields(beanClass,
                fields::add,
                field -> field.isAnnotationPresent(Alias.class));
        return fields;
    }

    private Optional<PropertyDescriptor> findExistingPropertyDescriptor(String propertyName, Class<?> propertyType) {
        return propertyDescriptors
                .stream()
                .filter(pd -> pd.getName().equals(propertyName) && pd.getPropertyType().equals(propertyType))
                .findAny();
    }

    private void addAliasPropertyDescriptor(String[] values, PropertyDescriptor propertyDescriptor) {
        for (String value : values) {
            if (!value.isEmpty()) {
                try {
                    this.propertyDescriptors.add(new PropertyDescriptor(
                            value, propertyDescriptor.getReadMethod(), propertyDescriptor.getWriteMethod()));
                } catch (IntrospectionException e) {
                    LOGGER.error("add field[{}] alias[{}] property descriptor error", propertyDescriptor.getName(),
                            value, e);
                }
            }
        }
    }

    @Override
    public BeanDescriptor getBeanDescriptor() {
        return this.delegate.getBeanDescriptor();
    }

    @Override
    public EventSetDescriptor[] getEventSetDescriptors() {
        return this.delegate.getEventSetDescriptors();
    }

    @Override
    public int getDefaultEventIndex() {
        return this.delegate.getDefaultEventIndex();
    }

    @Override
    public PropertyDescriptor[] getPropertyDescriptors() {
        return this.propertyDescriptors.toArray(new PropertyDescriptor[0]);
    }

    @Override
    public int getDefaultPropertyIndex() {
        return this.delegate.getDefaultPropertyIndex();
    }

    @Override
    public MethodDescriptor[] getMethodDescriptors() {
        return this.delegate.getMethodDescriptors();
    }

    @Override
    public BeanInfo[] getAdditionalBeanInfo() {
        return this.delegate.getAdditionalBeanInfo();
    }

    @Override
    public Image getIcon(int iconKind) {
        return this.delegate.getIcon(iconKind);
    }

    static class PropertyDescriptorComparator implements Comparator<PropertyDescriptor> {

        @Override
        public int compare(PropertyDescriptor desc1, PropertyDescriptor desc2) {
            String left = desc1.getName();
            String right = desc2.getName();
            for (int i = 0; i < left.length(); i++) {
                if (right.length() == i) {
                    return 1;
                }
                int result = left.getBytes()[i] - right.getBytes()[i];
                if (result != 0) {
                    return result;
                }
            }
            return left.length() - right.length();
        }
    }
}