aclowkay
aclowkay

Reputation: 3887

Autowiring a list in spring, without configuration

How can I autowire a list using java, without configuration?

Say I have the following classes:

public abstract class A {
    public abstract doStuff();
}

public class B extends A {
    @Override
    public void doStuff() {
        System.out.println("I'm B");
    }
}

public class C extends A {
    @Override
    public void doStuff() {
        System.out.println("I'm C");
    }
}

And I have the class

public class Aggregator {
    @Autowired
    private List<A> stuffDoers;
    private void doAllStuff() {
        for(A a:stuffDoers) {
            a.doStuff();
        }
    }
}

How can I autowire some of A's implementation into the Aggregator without configuring a list in XML?

EDIT: I'm looking for a way to be able to control the members of a list

Upvotes: 2

Views: 1610

Answers (1)

metacubed
metacubed

Reputation: 7271

@Autowired always works with instances of a class, not types. You have defined 3 types: A, B and C, but have not created any instances from them.

To autowire, you need to create these instances, and also register them with Spring. This is where the XML config or Java config comes in. It is basically a short form for creating Spring-registered instances. So you can specify:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfiguration {

    @Bean
    public B someA() {
        return new B();
    }

    @Bean
    public C anotherA() {
        return new C();
    }

    @Bean
    public B evenMoreA() {
        return new B();
    }
}

This gives you 3 independent instance beans (not a list). For more details, see Java-based container configuration.

Now, Spring will do the job of finding all beans of type A in those packages, and populate your Aggregator class with all three beans correctly.

NOTE: These beans don't need to be in the same file. They can be declared anywhere in your @ComponentScan packages.


As asked in a comment, what if you want to have only some of those instances?

If you want only some of the beans added to your list, the situation is more tricky. You will need to move the excluded beans to a separate @Configuration class, in a different package. You should not add that new package to the Spring @ComponentScan packages, so Spring will not find those beans to add to the list. As far as I know, this is the only way.

Of course, if you want only a single bean, then as usual, you have to autowire it using @Qualifier and specify the bean name. In this case, you don't use a List, just the variable of type A.

Upvotes: 3

Related Questions