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

时间:2016-07-03 14:41:27

标签: java spring-mvc spring-boot

我的问题实际上是这个问题as seen here...的衍生产品,因此在继续之前检查该线程可能会有所帮助。

在我的Spring Boot项目中,我有两个实体SenderRecipient代表一个Customer并且几乎有相同的字段,所以我让它们扩展基类{{ 1}};

客户基类;

Customer

发件人域对象;

@MappedSuperclass
public class Customer extends AuditableEntity {

    @Column(name = "firstname")
    private String firstname;

    @Transient
    private CustomerRole role;

    public Customer(CustomerRole role) {
        this.role = role;
    }

    //other fields & corresponding getters and setters
}

收件人域对象;

@Entity
@Table(name = "senders")
public class Sender extends Customer {

    public Sender(){
        super.setRole(CustomerRole.SENDER);
    }
}

注意 - @Entity @Table(name = "recipients") public class Recipient extends Customer { public Recipient(){ super.setRole(CustomerRole.RECIPIENT); } } Sender除了角色外完全相同。通过将Recipient基类作为实体本身,可以轻松地将这些存储在单个客户表中,但我有意将这些实体分开,因为我有义务将每个客户类型保留在单独的数据库表。

现在,我在视图中有一个表单,用于收集Customer和&的详细信息。 Sender,例如,为了收集名字,我必须以不同方式命名表单字段,如下所示;

表单的发件人部分;

Recipient

表单的收件人部分;

<input type="text" id="senderFirstname" name="senderFirstname" value="$!sender.firstname">

但是,客户可用的字段太多了,我正在寻找一种方法,通过this question here中提到的注释将它们映射到pojo。但是,提供的解决方案there意味着我必须为两个域对象创建单独的代理并相应地注释字段,例如

<input type="text" id="recipientFirstname" name="recipientFirstname" value="$!recipient.firstname">

所以我非常好奇并且想知道,有没有办法将这个代理映射到多个@ParamName,以便基类例如可以注释如下?;

public class SenderProxy {

    @ParamName("senderFirstname")
    private String firstname;

    @ParamName("senderLastname")
    private String lastname;
    //...
}

public class RecipientProxy {

    @ParamName("recipientFirstname")
    private String firstname;

    @ParamName("recipientLastname")
    private String lastname;
    //...
}

然后可能找到一种基于注释选择字段值的方法??

1 个答案:

答案 0 :(得分:0)

张洁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();
        }
    }
}