找到了不写自定义conversionService的解决方案,使用@Lazy注解解决循环依赖。
类Configuration
如:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
@Lazy
private ConversionService mConversionService;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(aConverter());
registry.addConverter(bConverter());
}
@Bean
public AConverter aConverter() {
return new AConverter();
}
@Bean
public BConverter bConverter() {
return new BConverter(mConversionService);
}
}
AConverter
并且BConverter
两者都实现 了org.springframework.core.convert.converter.Converter<S,T>
,AConverter
将类转换A
为AA
并将类BConverter
转换B
为其中包含的另一个类A
。
更新
ConversionService
在构造函数中注入WebConfig
更好,可以避免字段注入:
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final ConversionService mConversionService;
@Autowired
public WebConfig(@Lazy ConversionService conversionService) {
mConversionService = conversionService;
}
}