【问题标题】:Java Config equivalent for conversionService / FormattingConversionServiceFactoryBeanConversionService / FormattingConversionServiceFactoryBean 的 Java Config 等效项
【发布时间】:2014-10-02 20:26:59
【问题描述】:

我有一个实体包含另一个实体,如下:

public class Order {

    @Id
    private int id;

    @NotNull
    private Date requestDate;

    @NotNull
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="order_type_id")
    private OrderType orderType;
}

public class OrderType {

    @Id
    private int id;

    @NotNull
    private String name;
}

我有一个 Spring MVC 表单,用户可以在其中提交新订单;他们必须填写的字段是请求日期并选择订单类型(这是一个下拉菜单)。

我正在使用 Spring Validation 来验证表单输入,该表单输入在尝试将 orderType.id 转换为 OrderType 时失败。

我编写了一个自定义转换器来将 orderType.id 转换为 OrderType 对象:

public class OrderTypeConverter implements Converter<String, OrderType> {

    @Autowired
    OrderTypeService orderTypeService;

    public OrderType convert(String orderTypeId) {

        return orderTypeService.getOrderType(orderTypeId);
    }
}

我的问题是我不知道如何使用 java config 向 Spring 注册这个转换器。我找到的 XML 等价物(来自 Dropdown value binding in Spring MVC)是:

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
       <list>
          <bean class="OrderTypeConverter"/>
       </list>
    </property>
</bean>

通过搜索网络,我似乎找不到等效的 java 配置 - 有人可以帮我吗?

更新

我已将 OrderTypeConvertor 添加到 WebMvcConfigurerAdapter 中,如下所示:

public class MvcConfig extends WebMvcConfigurerAdapter{

    ...

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new OrderTypeConvertor());
    }
}

但是我在 OrderTypeConvertor 中得到一个空指针异常,因为 orderTypeService 为空,大概是因为它是自动装配的,并且我使用了上面的 new 关键字。一些进一步的帮助将不胜感激。

【问题讨论】:

  • 你在这个类中也拼错了 OrderTypeConverter...

标签: java spring spring-mvc


【解决方案1】:

您需要做的就是:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{

    @Autowired
    private OrderTypeConvertor orderTypeConvertor;

    ...

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(orderTypeConvertor);
    }
}

【讨论】:

  • 感谢您的回复。我在 OrderTypeConverter 中得到一个 NPE,因为 orderTypeService 为空(它是自动连接的)。我已经更详细地更新了我原来的问题。
  • @smilin_stan 没问题!我完全更新了我的答案以反映您问题的变化
  • 解决方案是 @Autowired 而不是 new OrderTypeConverter()。很奇怪,但它有效!
  • 使用 springboot 2 现在应该实现 WebMvcConfigurer,因为 WebMvcConfigurerAdaptor 已被弃用。其余的保持不变。
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2012-12-15
  • 1970-01-01
  • 2011-01-10
  • 2010-09-12
  • 2014-09-08
相关资源
最近更新 更多