My application is implemented on Kotlin and I use spring boot 3.
I have a class like this:
import org.springframework.core.convert.converter.Converter
@Component
class MyConverter : Converter<SomeResult, List<UserDto>> {
...
}
I want to inject it(using interface!!!) to another component:
@Service
class MyService(
private val myConverter : Converter<SomeResult, List<UserDto>>
){
...
}
But I receive the error:
Parameter 1 of constructor in ******.MyService required a bean of type 'org.springframework.core.convert.converter.Converter' that could not be found.
How can I fix it ?
This trick perfectly works for converters without generics. For example:
Converter<UserDto, AnotherDto>
P.S.
My problem is I can't autowire by interface
private val myConverter : Converter<SomeResult, List<UserDto>>
As a workaround I can autowire by type(and it works)
private val myConverter : MyConverter
But it doesn't look perfect from my point of view
If you provide your converter as a @Bean
, you should be able to inject this converter (even as an interface)
@Configuration
class MyConfig {
// return type is interface
@Bean fun myConverter():Converter<SomeResult, List<UserDto>> = MyConverter()
}
// @Component <-- does not work
// provided as Bean in MyConfig <-- works
class MyConverter : Converter<SomeResult, List<UserDto>> {
override fun convert(source: SomeResult): List<UserDto> {
return listOf(UserDto())
}
}
@Service
class MyService(
private val myConverter : Converter<SomeResult, List<UserDto>>
){
}