首页 > 解决方案 > 实例化 Spring Bean

问题描述

我正在尝试根据我的要求调用两个不同的 bean。这两个 bean 实现了相同的接口。我必须使用两个基于数据中心的不同 db。我如何通过从 application.properties 传递参数在 springboot 应用程序中做到这一点

interface Data
{
   string getData(String query)
}



   @Component("oracle")
   class Oracle implements Data
   {
       //getMethod Code Here.
   }


   @Component("sqlserver")
   class SqlServer implements Data
   {
       //getMethod Code Here.
   }

目前我正在使用

  String db = appContext.getBean(propertiesfile.db//getting the value from properties file, Data::class.java)

并根据返回值调用特定的数据库。但是无论如何我只能基于 app.properties 实例化一个 bean 意味着不在appContext.getBean每个请求中使用

标签: javaspringspring-bootspring-webflux

解决方案


根据我最终使用的建议@ConditionalOnProperty

这个链接帮助我解决了这个问题。

https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty


推荐阅读