Cork Kochi
Cork Kochi

Reputation: 1891

How to dynamically inject different implementation for the same Interface using spring

I have one interface and two implementations for this interface

Interface definition:

public interface DoSomething {}

Two implementations:

public ImplementationOne implements DoSomething{}
public ImplementationTwo implements DoSomething{}

Then inside another class, I want to get a different implementaion (either ImplementationOne or ImplementationTwo) based on the condition, how can I do that using Spring?

Something like..

Public ServiceManager {
Private DoSomething doSomething = null;
Public void do() {
If (condition1) {
doSomething = new ImplementationOne();
} else {
doSomething = new ImplementationTwo();
}
}
}

Upvotes: 0

Views: 1242

Answers (2)

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

Another option to consider is have a configuration bean - for example -

@Configuration
public class EntityRepositoryConfiguration {

    private Map<Entity, EntityRepository> entityEntityRepositoryMap = new HashMap<>();

    protected EntityRepositoryConfiguration() {
        entityEntityRepositoryMap.put(Entity.Book, new BookRepository());

    }

    @Bean
    public EntityRepository getByEntityType(Entity entity) {
        return entityEntityRepositoryMap.get(entity);
    }

}

And then inject the configuration bean to your other beans and use the getEntityType method (for example) to get beans injected.

Upvotes: 1

Moshe Arad
Moshe Arad

Reputation: 3733

You should definitely auto wire ApplicationContext type using @Autowire annotation. Then if you did it like this:

@Autowire
ApplicationContext context

Then you should get your desired bean like this:

context.getBean(yourDesiredType.class)

Like that you can get any bean you want to be placed under any matching type according to your example.

Upvotes: 1

Related Questions