[英]Autowiring Generic in Spring Boot / Kotlin
目前,我有以下课程:
interface Mapper<IN, OUT> {
fun map(input: IN): OUT
}
@Service
class ContractPhaseMapper: Mapper<Contract, List<ContractPhase>> {
override fun map(input: Contract): List<ContractPhase> = contract.phases.map {
ContractPhase(...)
}
}
@Service
class ContractPhaseProcessor(private val contractPhaseMapper: Mapper<Contract, List<ContractPhase>>) {
fun createResponse(contracts: List<Contract>) = SomeResponse(
contractPhases = contracts.map { contractPhaseMapper.map(it) }.flatten()
)
}
不幸的是,这导致Spring用以下消息纾困:
Parameter # of constructor in my.package.ContractPhaseProcessor required a bean of type 'my.package.mapper.Mapper' that could not be found.
如果我尝试像Mapper<Contract, Customer>
这样的Mapper<Contract, Customer>
它会很好地工作。
我还尝试使用@Qualifier
使其明确使用该服务,但仍然无法正常工作。
有人知道这个问题的简单解决方案吗?
我无法弄清楚为什么您的方法行不通-但我已经重现了您的问题,并建议您采用一种解决方法:如果您使用@Condiguration
注释类而不是@Service
注释来配置Spring Bean,那么一切正常:
class ContractPhaseMapper: Mapper<Contract, List<ContractPhase>> {
override fun map(input: Contract): List<ContractPhase> = ...
}
class ContractPhaseProcessor(private val contractPhaseMapper: Mapper<Contract, List<ContractPhase>>) {
fun createResponse(contracts: List<Contract>) : String = ...
}
@Configuration
open class MyConfiguration {
@Bean
open fun mapper() : Mapper<Contract, List<ContractPhase>> = ContractPhaseMapper()
@Bean
open fun processor(mapper: Mapper<Contract, List<ContractPhase>>) : ContractPhaseProcessor = ContractPhaseProcessor(mapper)
}
// Main function, that wires up the application context deriving bean definitions
// from the given class MyConfiguration, annotated with @Configuration
fun main() {
AnnotationConfigApplicationContext(MyConfiguration::class.java).use { context ->
val component = context.getBean(ContractPhaseProcessor::class.java)
println(component)
println(component.createResponse(listOf()))
}
}
希望这可以帮助您解决问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.