找到了不写自定义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;
}
}