Please look at the example below:
class Foo
class Bar
class Baz
@Component
class FooToBarConverter : Converter<Foo, Bar> {
override fun convert(source: Foo) = Bar()
}
@Component
class BarToBazConverter : Converter<Bar, Baz> {
override fun convert(source: Bar) = Baz()
}
@RestController("/test")
class TestController(val conversionService: ConversionService) {
@GetMapping
fun get() = "test: " + conversionService.convert(Foo(), Baz::class.java)
// must convert Foo to Bar, then Bar to Baz, but throws an exception instead
}
Is there any way to achieve the desired behavior without reinventing the wheel?
You Can use
@Autowired private List<Converter> allConverter;
This will inject all beans that are implementing the Converter interface.
Now you can loop throw the list and class convert method.
allConverter.stream().forEach(Converter::convert);
To Manage the order of converters, you need to sort list.