假设我有几个实现单个接口的Spring组件:
interface Haha
@Component class HahaImpl1: Haha {
@Autowired lateinit var repo: JpaRepository<Data, Long>
}
@Component class HahaImpl2: Haha
@Service
class Yoyo {
@Autowired lateinit var haha: Haha
}
如何将正确的依赖项注入我的Yoyo
服务,我可以在application.properties
文件中指定?
myApp.haha=impl1
我可以创建一个配置,但是我必须删除@Component
注释,这是我不想要的,因为在Haha实现类中我会注入其他bean(服务,控制器等): / p>
@Configuration
class MyConfiguration {
@Bean
@ConditionalOnProperty(name = ["myApp.haha"], havingValue = "impl1", matchIfMissing = true)
fun config1(): Haha = HahaImpl1()
@Bean
@ConditionalOnProperty(name = ["myApp.haha"], havingValue = "impl2")
fun config2(): Haha = HahaImpl2()
}
有什么想法吗?感谢。
答案 0 :(得分:4)
您可以通过将@ConditionalOnProperty
移动到bean类并完全删除@Configuration
类(或者至少删除处理HaHa
个实例的部分)来解决问题:
interface HaHa
@Component
@ConditionalOnProperty(name = "myApp.haha", havingValue = "impl1", matchIfMissing = true)
class HahaImpl1: Haha {
@Autowired
lateinit var repo: JpaRepository<Data, Long>
}
@Component
@ConditionalOnProperty(name = "myApp.haha", havingValue = "impl2")
class HahaImpl2: Haha {
// ...
}
这样,您始终可以获得HaHa
的一个实例,并且仅基于缺少属性的情况。这是有效的,因为@ConditionalOnProperty
可以显示{{1}}。
答案 1 :(得分:0)
解决方案是从所有Haha实现类中删除@Component
注释。
interface Haha
class HahaImpl1: Haha {
@Autowired lateinit var repo: JpaRepository<Data, Long>
}
class HahaImpl2: Haha
@Service
class Yoyo {
@Autowired lateinit var haha: Haha
}
@Configuration
class MyConfiguration {
@Bean
@ConditionalOnProperty(name = ["myApp.haha"], havingValue = "impl1", matchIfMissing = true)
fun config1(): Haha = HahaImpl1()
@Bean
@ConditionalOnProperty(name = ["myApp.haha"], havingValue = "impl2")
fun config2(): Haha = HahaImpl2()
}
application.properties
:
myApp.haha=impl1
#myApp.haha=impl2