Java Config等效于conversionService / FormattingConversionServiceFactoryBean
问题内容:
我有一个包含另一个实体的实体,如下所示:
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中注册此转换器。我发现从Spring
MVC的Dropdown值绑定中等效的XML 是:
<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为null,大概是因为它是自动装配的,并且我使用了上面的new关键字。一些进一步的帮助,将不胜感激。
问题答案:
您需要做的是:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{
@Autowired
private OrderTypeConvertor orderTypeConvertor;
...
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(orderTypeConvertor);
}
}