Prabhakaran
Prabhakaran

Reputation: 209

Spring dependency injection with multiple implementation for an interface

So, this interface has 2 implementations. I want to validate the input with all the implementations of the interface and return the implementation object whatever satisfies the condition.

Interface:

interface SomeInterface {
     boolean someCheck(int n);
} 

Implementation 1:

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

Implementation 2:

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

Can I use the dependency injection concept here?

Upvotes: 0

Views: 372

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42431

Assuming both implementations are spring beans, you can inject both implementations in the list:

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
   }

   
}

Upvotes: 2

Related Questions