0

I want to instantiate a generic bean with a type parameter, and have the correct dependents wired based on this type parameter.

Suppose I have:

@Named
public Parent<T> {

   @Inject
   Parent(Child<T> c) {
          ...
   }

}

public interface Child<T> {}

@Named
public class ChildString implements Child<String> {} 

@Named
public class ChildInteger implements Child<Integer> {}

And then I want to use Parent like this:

@Named
public class UseParent {

   @Inject
   Parent<String> p;

}

Spring will complain with "expected single matching bean but found 2: childString, childInteger".

What is the best way to have wire my beans in this scenario?

tekumara
  • 8,357
  • 10
  • 57
  • 69

1 Answers1

0

I haven't found a satisfactory way of doing this. The solution I'm using for now is to create a subclass of Parent that specifies the generic type, eg:

@Named
public ParentString {

   @Inject
   ParentString(Child<String> c) {
          super(c);
   }

}

@Named
public class UseParent {

   @Inject
   ParentString p;

}
tekumara
  • 8,357
  • 10
  • 57
  • 69