• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

access bean id programatically

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is it possible to access the id of a bean declared in the applicationContext.xml (I suspect not)
I have defined a bean like this:



I would like to access the id 'testBean' programmatically.





 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Stu,
If you look in the JavaDocs, there are a number of different ways to get the bean by its bean ID. The key is to get hold of the ApplicationContext, which is the way to access the beans.

The most direct way is as follows:

I use this approach in a lot of my unit tests.

Another way I've done this is in web applications where I'm hooking Spring components into an existing web application. In this case, I use the ContextLoaderListener to configure the beans when the web application context is loaded. Then, I can use the following snippet:


I hope this helps,

Mark
 
Stu Johns
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sorry, the question was misunderstood, yes I can get the bean from the spring container by the id, once i have it is there any way to get the id of that bean, (I know in my example i already know it, but in reality I may not for example if it was part of a map.)
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can get the name of a bean when it is instantiated, by making it BeanNameAware. But check carefully the API for org.springframework.beans.factory.BeanNameAware. (And I don't see the point of using the bean name to keep it in a map)
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic