0

I've a class where I've autowired a list of type

Class A{
   @Autowired
   List<Super> supers;
}

@Qualifier("B")
Class BSuperImpl implements Super{....}

@Qualifier("C")
Class CSuperImpl implements Super{....}

@Qualifier("D")
Class DSuperImpl  implements Super{....}

Now I want to write a code in Class A, where I can look upon the bean, based upon the qualifier like following, Without making my bean aware of the Context. Using Spring MVC 4.3

Class A {

   @Autowired
   List<Super> supers;

   void process(String str){
       // Code to do supers.applyMethod(getTheBeanWithQualifierAs(str));
      }
}
ThrowableException
  • 1,168
  • 1
  • 8
  • 29
  • `supers` as I understand is a `List`. Please share details on how to call `applyMethod()` ? – R.G Apr 30 '20 at 05:25

1 Answers1

1

For what it's worth

@Service
public class A {

    @Autowired
    List<Super> supers;

    void process(String str) {
        for(Super sup : supers) {
            if(str.equals((sup.getClass().getAnnotation(Qualifier.class).value()))){
                // executes when the bean qualifier name and str matches.
            }
        }

    }
}

---- Another attempt ----

Interface

public interface Super {
    String getQualifier();
}

Sample Implemenation

@Service
@Qualifier(BSuperImpl.QUALIFIER)
public class BSuperImpl implements Super {

    static final String QUALIFIER = "B";

    @Override
    public String getQualifier() {
        return QUALIFIER;
    }

}

A

@Service
public class A {

    @Autowired
    Map<String,Super> supers;

    void process(String str) {
        System.out.println(supers);
        for(String beanName : supers.keySet()) {
            if(str.equals(supers.get(beanName).getQualifier())){
                // execute the logic 
            }
        }
    }
}

When a bean is required from the container not through dependency injection , one way or another you will need to refer the application context.

In this approach , the usage of @Qualifier is not required infact . Usage of map is to demonstrate a possiblity that the beanName can also be passed as parameter to the method .

R.G
  • 6,436
  • 3
  • 19
  • 28