spring - 有条件的@Autowired?

标签 spring factory autowired

我有一个我 Autowiring 的 HsqldbReconciler(用于与 HSQLDB 数据库“工作”),例如:

@Autowired
HsqldbReconciler hsqldbReconciler;

将来会有 OracleReconciler、MssqlReconciler 等。我需要根据用户选择的连接类型来使用它们。

我应该如何实现?通常我会有一种工厂,它只返回所需的协调器。我目前可以想象,spring 的唯一方法是 Autowiring 每个 Reconciler 的一个实例,然后在代码中使用它们中的一个。有没有更好的办法?

最佳答案

制作一个包含所有 bean 的工厂类,例如

@Component
class Factory{
  @Autowired HsqldbReconciler hsqldb;
  @Autowired OracleReconciler oracle;
  @Autowired MssqlReconciler mssql;

  public Object getInstance(String type){
    switch(type){
     case "mssql" : return mssql;
     case "oracle" : return oracle;
     // and so on  
     default : return null;
   }

  }

}

现在使用这个工厂如下
class SomeClass{

  @Autowired private Factory factory;

  public Object someMethod(){
    Object reconciler = factory.getInstance("mssql");
    ((MssqlReconciler)reconciler).someMethod();
  }
}

关于spring - 有条件的@Autowired?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054789/

相关文章:

c++ - Boost::log 静态工厂方法

caSTLe-windsor - 温莎城堡 : A better way to implement 2 levels of (nested) factories?

java - Spring Boot CommandLineRunner 和构造函数注入(inject)

spring - spring 的默认 Autowiring 是什么?

spring - 使用 Spring-boot 配置的 Logstash/Logback 设置

java - 如何在 Spring 中获取 Cognito 用户的组?

java - Spring : detached entity passed to persist

java 工厂方法和泛型

java - Autowiring List<List<String>> 出具有未知键长度的属性文件

java - 如何在 Spring 框架前端接收验证消息?