【问题标题】:Spring dependency injection with multiple implementation for an interface具有多个接口实现的 Spring 依赖注入
【发布时间】:2021-02-18 16:17:25
【问题描述】:

所以,这个接口有 2 个实现。我想用接口的所有实现来验证输入,并返回满足条件的实现对象。

界面:

interface SomeInterface {
     boolean someCheck(int n);
} 

实施 1:

public class SomeClass implements SomeInterface {
   public boolean someCheck(int n) {
      // returns true if n is less than 10
   }
}

实施 2:

public class AnotherClass implements SomeInterface {
   public boolean someCheck(int n) {
      // returns true if n is greater than 10
   }
}

我可以在这里使用依赖注入的概念吗?

【问题讨论】:

    标签: java spring spring-boot dependency-injection


    【解决方案1】:

    假设两个实现都是spring bean,你可以在列表中注入两个实现:

    public class Validator {
    
       @Autowired
       private List<SomeInterface> allImplementations;
        
       public boolean validate(int n) {
          for(SomeInterface impl : allImplementations) {
              if(!impl.someCheck(n)) {
                  return false;
              }
           }
           return true; // all validations passed
       }
    
       
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 2014-10-06
      • 2014-08-08
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      相关资源
      最近更新 更多