Nick Carfagno
Nick Carfagno

Reputation: 13

Inject instance of all subclasses into a list of parent classes with Spring

I have a parent class:

@Component
public abstract class MyClass {
}

This class has three subclasses, MyClass2, MyClass3, and MyClass4

@Component
public class MyClass2 extends MyClass{
}
@Component
public class MyClass3 extends MyClass{
}
@Component
public class MyClass4 extends MyClass{
}

I have another class, MyClassList that has a list of MyClass that I want to be injected with all subclasses of MyClass (MyClass2, MyClass3, MyClass4).

@Component
public class MyClassList {
    public List<MyClass> classes;

    @Autowired
    public void setMyClass(List<MyClass> classes) {
        this.classes = classes;
    }

    public void printClassListSize(){
        System.out.println(classes.size());
    }
}

When I create a MyClassList object and call printClassListSize(), the list is always null. How can I get the classes list to be auto injected with an instance of each subclass?

Upvotes: 0

Views: 1280

Answers (2)

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 17510

When I create a MyClassList object (...)

This is the issue. You don't get to create the object yourself but you should use the one managed by Spring so that you can take advantage of Spring Dependency Injection feature.

You can do that either by injecting in on another Spring-managed Bean (preferred approach) or you get it yourself programmatically:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyClassList myClassList = ctx.getBean(MyClassList.class);

Upvotes: 0

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

Replace with constructor-injection

@Component
public class MyClassList {
    private final List<MyClass> classes;

    @Autowired
    public MyClassList(List<MyClass> classes) {
        this.classes = classes;
    }

    public void printClassListSize(){
        System.out.println(classes.size());
    }
}

Upvotes: 1

Related Questions