Home > Software design >  How to access all injected variables of a class by using variable type in java with spring boot?
How to access all injected variables of a class by using variable type in java with spring boot?

Time:08-11

I have a highly specific question. I am using Spring boot with Java. Suppose I have a Verifier interface which has a verify method. Suppose I have 3 concrete implementations of this say VerifierA, VerifierB, VerifierC. If I have a VerificationService class where these 3 verifiers are being injected, Is there any way by which I can access all these verifiers inside a method of VerificationService class? The code is as given below

public Interface Verifier {
   public void verify(Obj obj);
}

@Component
public class VerifierA implements Verifier{
    @Override public void verify(Obj obj) { 
     // do somethingA
    }
}


@Component
public class VerifierB implements Verifier{
    @Override public void verify(Obj obj) { 
     // do somethingB
    }
}


@Component
public class VerifierC implements Verifier{
    @Override public void verify(Obj obj) { 
     // do somethingC
    }
}
@Service
public VerificationService() {

    @Autowired private final Verifier verifierA;

    @Autowired private final Verifier verifierB;

    @Autowired private final Verifier verifierC;

    public void test(Obj obj) {
        //here I want to call verify method of all the 3 verifiers without explicitly calling all verifiers by variable names

       //i want to do something like following
      for(Verifier verifier: listOfInjectedVerifiers) {
          verifier.verify(obj);
      }
      // the above is not working code. This is the behaviour I want
   }

}

Is there any way to do this? Thanks in advance

CodePudding user response:

Spring can inject all beans that implement an interface. To do so, declare that your component accepts a List of that interface type. Using constructor injection, that would look like this (untested pseudo-code):

@Service
public class VerificationService {
    private List<Verifier> verifiers;

    public VerificationService(List<Verifier> verifiers) {
        this.verifiers = verifiers;
    }

    public void verify(Object object) {
        for (Verifier verifier : verifiers) {
            verifier.verify(object);
        }
    }

}
  • Related