Ram ji Soni
Ram ji Soni

Reputation: 1

Getting bean based on key in Spring4 Annotationbased

I had configure Spring 4 with WebApplicationInitializer. There are two service named Item1Service and Item2Service.

But In controller I need to find one service based on key provided by user. If there were xml based configuration then I can get by id.

But how I can get AnnotationConfigWebApplicationContext object in controller, so that I can get my bean based on key.

I have used @Service(value="item1") and @Service(value="item2")

Kindly help me out on this

Upvotes: 0

Views: 36

Answers (2)

so-random-dude
so-random-dude

Reputation: 16475

If it's only a couple of implementations you have to choose from, then you have one more option. Autowire all services in the controller and switch at runtime based on the key. (Note: I will not prefer this, if the service implementation count exceeds 3. It will make your code unreadable as well as it will unnecessarily create service reference variables in controller)

@Autowired @Qualifier("item1")
    ItemService item1Service;

@Autowired @Qualifier("item2")
    ItemService item2Service;

Upvotes: 0

slc84
slc84

Reputation: 61

You should be able to autowire your application context into your controller (or wherever you are performing the lookup) so that you can then call the getBean method with whatever input the user provided.

@Autowired
private ApplicationContext appContext;

then in your method:

MyService s = appContext.getBean(input);

Upvotes: 1

Related Questions