smi*_*tan 6 java spring spring-mvc
我有一个包含另一个实体的实体,如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
我有一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道如何使用java配置使用Spring注册此转换器.我发现的XML等价物(来自Spring MVC中的Dropdown值绑定)是:
<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>
Run Code Online (Sandbox Code Playgroud)
从搜索网络我似乎找不到相当于java配置 - 有人可以帮助我吗?
UPDATE
我已将OrderTypeConvertor添加到WebMvcConfigurerAdapter,如下所示:
public class MvcConfig extends WebMvcConfigurerAdapter{
...
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new OrderTypeConvertor());
}
}
Run Code Online (Sandbox Code Playgroud)
但是我在OrderTypeConvertor中得到一个空指针异常,因为orderTypeService为null,可能是因为它是自动装配的,我使用了上面的new关键字.一些进一步的帮助将不胜感激.
您需要做的就是:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{
@Autowired
private OrderTypeConvertor orderTypeConvertor;
...
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(orderTypeConvertor);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7081 次 |
最近记录: |