Spring Data DomainClassConverter not working (in c

2019-03-22 03:38发布

I'm trying to setup the Spring Data/JPA DomainClassConverter to automatically convert (String) id's to the domain classes itself.

My project is uses Java Config (so no xml).

In my WebConfig I have currently:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DomainClassConverter<DefaultFormattingConversionService>((DefaultFormattingConversionService) registry));
    }
}

This seems to hook up the DomainClassConverter successfully as I can see it inside the conversion service when printing that:

ConversionService converters =
  ..<default converters>..
  org.springframework.data.repository.support.DomainClassConverter@6ea4ce0d, org.springframework.core.convert.support.IdToEntityConverter@5d3f03b, org.springframework.core.convert.support.ObjectToObjectConverter@1d40b47a

But when submitting a nested form (Order with Customer ref) the Customer is not converted automatically and hence I get a:

Failed to convert property value of type java.lang.String to required type org.mycomp.domain.Customer for property customer; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.mycomp.domain.Customer] for property customer: no matching editors or conversion strategy found

I'm wondering if I'm doing something wrong here?

2条回答
等我变得足够好
2楼-- · 2019-03-22 04:06

The exception is telling you that you need a custom converter to turn a String into a Customer. You'll have to tokenize the input and map it into Customer fields. That's true for all your domain classes.

A Google search also lead me to a thread in the Spring forum:

http://forum.springsource.org/showthread.php?122944-Help-with-DomainClassConverter-configuration

It suggests that there might be a bug, depending on which version of Spring you're using.

查看更多
老娘就宠你
3楼-- · 2019-03-22 04:26

DomainClassConverter should be declared as a bean (because it's ApplicationContextAware), and it registers itself in ConversionService automatically, so that you don't need to register it manually:

@Bean @Autowired
public DomainClassConverter domainClassConverter(ConversionService cs) {
    return new DomainClassConverter(cs);
}
查看更多
登录 后发表回答