Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}

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).

I am using Spring Validation to validate the form input which fails as it is trying to convert an orderType.id to an 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);
    }
}

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>

From searching the web I can't seem to find a java config equivalent - can someone please help me out?

UPDATE

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());
    }
}

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.

like image 683
smilin_stan Avatar asked Aug 09 '14 13:08

smilin_stan


1 Answers

All you need to do in your case is:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{

    @Autowired
    private OrderTypeConvertor orderTypeConvertor;

    ...

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(orderTypeConvertor);
    }
}
like image 147
geoand Avatar answered Oct 20 '22 06:10

geoand