【发布时间】: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