Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

access bean id programatically

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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)
 
Maybe he went home and went to bed. And took this tiny ad with him:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
    Bookmark Topic Watch Topic
  • New Topic