Java Config等效于conversionService / FormattingConversionServiceFactoryBean [英] Java Config equivalent for conversionService / FormattingConversionServiceFactoryBean
问题描述
我有一个包含另一个实体的实体,如下所示:
I have an entity that contains another entity, as follows:
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表单,用户可以提交新订单;他们必须填写的字段是请求日期并选择订单类型(这是一个下拉列表)。
I have a Spring MVC form where a user can submit a new order; the fields they have to fill in are the Request Date and select an Order Type (which is a drop-down).
我使用Spring Validation来验证表单输入因为尝试将orderType.id转换为OrderType而失败。
I am using Spring Validation to validate the form input which fails as it is trying to convert an orderType.id to an OrderType.
我编写了一个自定义转换器,将orderType.id转换为OrderType对象:
I have written a custom converter to convert an orderType.id into an OrderType object:
public class OrderTypeConverter implements Converter<String, OrderType> {
@Autowired
OrderTypeService orderTypeService;
public OrderType convert(String orderTypeId) {
return orderTypeService.getOrderType(orderTypeId);
}
}
我的问题是我不知道如何注册这个转换器使用Spring使用java配置。我找到的XML等价物(来自 Spring MVC中的Dropdown值绑定)是:
My problem is I don't know how to register this converter with Spring using java config. The XML equivalent I've found (from Dropdown value binding in Spring MVC) is:
<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的配置 - 有人可以请帮助我out?
From searching the web I can't seem to find a java config equivalent - can someone please help me out?
UPDATE
我已将OrderTypeConvertor添加到WebMvcConfigurerAdapter,如下所示:
I have added the OrderTypeConvertor to the WebMvcConfigurerAdapter as follows:
public class MvcConfig extends WebMvcConfigurerAdapter{
...
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new OrderTypeConvertor());
}
}
但是我在OrderTypeConvertor中得到一个空指针异常,因为orderTypeService是null,大概是因为它是自动装配的,我使用了上面的新关键字。一些进一步的帮助将不胜感激。
However I get a null pointer exception in OrderTypeConvertor as orderTypeService is null, presumably because it is autowired and I've used the new keyword above. Some further help would be appreciated.
推荐答案
您需要做的就是:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{
@Autowired
private OrderTypeConvertor orderTypeConvertor;
...
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(orderTypeConvertor);
}
}
这篇关于Java Config等效于conversionService / FormattingConversionServiceFactoryBean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!