0

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();
}
}
}
5
  • Could you provide us with an example where this DoSomething is used? Do you use it in an @Autowired constructor/field/setter...? Does it have to change when the using class is already instanciated Commented May 1, 2017 at 11:43
  • How do you intend to use Spring? Xml or annotation configuration? I figure the best option would be to get a handle to the Spring ApplicationContext and get a managed bean by name or concrete class. Commented May 1, 2017 at 11:44
  • Btw: looks like a duplicate of <stackoverflow.com/questions/19231875/…> Commented May 1, 2017 at 11:51
  • Possible duplicate of Choose which implementation to inject at runtime spring Commented May 1, 2017 at 11:56
  • There are many ways. It often depends on what kind of condition you want to base it on. You can use profiles, you can use the Spring Expression language inside XML configs for example, or you could use FactoryBean's when things get complex, and I'm sure there are many other ways. Commented May 1, 2017 at 11:57

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.