加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Config等效于conversionService / FormattingConversionSer

发布时间:2020-12-15 01:02:06 所属栏目:Java 来源:网络整理
导读:我有一个包含另一个实体的实体,如下所示: 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 Or
我有一个包含另一个实体的实体,如下所示:
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配置使用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配置 – 有人可以帮助我吗?

UPDATE

我已将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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读