问题描述
我正在尝试将Spring Data/JPA DomainClassConverter设置为自动将(字符串)id转换为域类本身.
I'm trying to setup the Spring Data/JPA DomainClassConverter to automatically convert (String) id's to the domain classes itself.
我的项目使用Java Config(因此没有xml).
My project is uses Java Config (so no xml).
在我的WebConfig中,我目前有:
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));
}
}
这似乎成功连接了DomainClassConverter,因为在打印该代码时我可以在转换服务中看到它:
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?
推荐答案
DomainClassConverter
应该声明为bean(因为它是ApplicationContextAware
),并且它会自动在ConversionService
中注册自己,这样您就不必需要手动注册:
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);
}
这篇关于Spring Data DomainClassConverter不起作用(与Java Config结合使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!