要解决任何循环依赖关系,请执行以下步骤(Spring Boot v5.2.1):
注册一个简单的转换服务
@Configuration
public class ConverterProvider {
@Bean
public ConversionService conversionService() {
ConversionService conversionService = new GenericConversionService();
return conversionService;
}
}
注入您的自定义转换器
@Component
public class ConvertersInjection {
@Autowired
private GenericConversionService conversionService;
@Autowired
private void converters(Set<Converter> converters) {
converters.forEach(conversionService::addConverter);
}
}
转换器甚至可以自动连接您的转换服务
@Component
public class PushNotificationConverter implements Converter<PushNotificationMessages.PushNotification, GCM> {
@Lazy
@Autowired
private ConversionService conversionService;
@Override
public GCM convert(PushNotificationMessages.PushNotification source) {
GCM gcm = new GCM();
if (source.hasContent()) {
PushNotificationMessages.PushNotification.Content content = source.getContent();
if (content.hasData()) {
conversionService.convert(content.getData(), gcm.getData().getClass());
} else if (content.hasNotification()) {
conversionService.convert(content.getNotification(), gcm.getNotification().getClass());
}
}
return gcm;
}
}