英文:
How to inject Converter which returns list of generic type in Kotlin?
问题
我的应用程序是用Kotlin实现的,我使用Spring Boot 3。
我有一个类像这样:
import org.springframework.core.convert.converter.Converter
@Component
class MyConverter : Converter<SomeResult, List<UserDto>> {
...
}
我想要将它(使用接口!!!)注入到另一个组件中:
@Service
class MyService(
private val myConverter: Converter<SomeResult, List<UserDto>>
){
...
}
但是我收到了错误消息:
Parameter 1 of constructor in ******.MyService required a bean of type
'org.springframework.core.convert.converter.Converter' that could not
be found.
我该如何修复它?
P.S.
这个技巧对于没有泛型的转换器完美适用。例如:
Converter<UserDto, AnotherDto>
P.S.
我的问题是我不能按接口自动装配
private val myConverter: Converter<SomeResult, List<UserDto>>
作为一种解决方法,我可以按类型自动装配(它可以工作)
private val myConverter: MyConverter
但从我看来,这不是完美的。
英文:
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 ?
P.S.
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
答案1
得分: 1
如果您将您的转换器作为@Bean
提供,您应该能够注入这个转换器(甚至作为一个接口)。
@Configuration
class MyConfig {
// 返回类型是接口
@Bean fun myConverter(): Converter<SomeResult, List<UserDto>> = MyConverter()
}
// @Component <-- 不起作用
// 在MyConfig中作为Bean提供 <-- 起作用
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>>
){
}
英文:
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>>
){
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论