实例化Spring Bean

huangapple go评论71阅读模式
英文:

Instantiate Spring Bean

问题

我正试图根据我的需求调用两个不同的bean。这两个bean都实现了相同的接口。根据数据中心,我必须使用两个不同的数据库。我如何在Spring Boot应用中通过从application.properties传递参数来实现这一点?

interface Data {
    String getData(String query);
}

@Component("oracle")
class Oracle implements Data {
    // 在这里编写方法代码。
}

@Component("sqlserver")
class SqlServer implements Data {
    // 在这里编写方法代码。
}

目前我正在使用:

String db = appContext.getBean(propertiesfile.db //从属性文件获取值,Data::class.java)

并根据返回值调用特定的数据库。但是否有一种方法可以根据app.properties仅实例化一个bean,而不是在每个请求中都使用appContext.getBean

英文:

I am trying to call two different beans based on my requirement.This two beans are implementing same interface.I have to use two diffrent db's based on data center.How I can do that in springboot application by passing a parameter from application.properties

interface Data
{
   string getData(String query)
}



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


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

Currently I am using

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

and calling particular db based on return value.But is there anyway I can only instantiate one bean based on app.properties means not using appContext.getBeanin every request

答案1

得分: 0

根据建议,我最终使用了 @ConditionalOnProperty

这个链接对我解决这个问题帮助很大。

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

英文:

As per suggestions I ended up Using @ConditionalOnProperty

This link helped me lot resolving this issue.

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

huangapple
  • 本文由 发表于 2020年9月23日 06:51:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64018696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定