假设我有几个 Spring 组件实现一个接口(interface):
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
}
如何将正确的依赖项注入(inject)到我的 Yoyo
服务中,我可以在 application.properties
文件中指定该依赖项?
myApp.haha=impl1
我可以创建一个配置,但随后我必须删除 @Component
注释,这是我不想要的,因为在 Haha 实现类中我会注入(inject)其他 bean(服务、 Controller 、等):
@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()
}
有什么想法吗?谢谢。
最佳答案
您可以通过将 @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
可以出现在 Method or a Type 上。 .
关于java - @Autowired 基于 application.properties 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828988/