I have an object that contains another object, as shown below:
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; }
I have a Spring MVC form where a user can submit a new order; the fields they need to fill in is the Request Date and select the Order Type (which is drop-down).
I use Spring Validation to validate the input of a form that fails because it is trying to convert orderType.id to OrderType.
I wrote my own converter to convert orderType.id to an OrderType object:
public class OrderTypeConverter implements Converter<String, OrderType> { @Autowired OrderTypeService orderTypeService; public OrderType convert(String orderTypeId) { return orderTypeService.getOrderType(orderTypeId); } }
My problem: I do not know how to register this converter with Spring using java config. The XML equivalent I presented (from the binding of the value of a drop-down list 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>
From a search on the Internet, I cannot find the equivalent of java config - can someone please help me?
UPDATE
I added OrderTypeConvertor to WebMvcConfigurerAdapter as follows:
public class MvcConfig extends WebMvcConfigurerAdapter{ ... @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new OrderTypeConvertor()); } }
However, I get a null pointer exception in OrderTypeConvertor because orderTypeService is NULL, apparently because it is auto-updated, and I used the new keyword above. Some additional help would be appreciated.