This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Spring and the fly likes Lifecycle of Spring Bean. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Lifecycle of Spring Bean. " Watch "Lifecycle of Spring Bean. " New topic

Lifecycle of Spring Bean.

Siddharth Bhargava
Ranch Hand

Joined: Feb 23, 2007
Posts: 268
Hi Friends,
Could you please explain me the lifecycle methods namely BeanNameAware's setBeanName() and BeanFactoryAware's setBeanFactory() theorotically as well as practically. I am unable to understand it conceptually. Please also let me know there usage with the help of an practical example.

Thanks and Regards,
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

First, for your own code, when you implement a Spring interface, you couple your code to Spring, and even Spring doesn't want you to do that.

Basically those interfaces methods get called right after your bean is instantiated and all dependencies have been injected and properties set. It will then call those methods passing in Spring classes.

So BeanNameAware will allow the bean to know what name/id you gave it in its configuration. Usually this is used because you want to log something and include the name of the bean that is logging it.

BeanFactoryAware will allow the bean to have a reference to the BeanFactory, this is just like ApplicationContextAware where the bean will get a reference to the ApplicationContext. So now directly in your bean you can call getBean(). Most common scenario is you have an EJB and you want to get one of your Spring Beans into your EJB, but you can't use dependency injection so it is your responsibility to call getBean in the EJB.

So, don't implement these interfaces yourself, unless there is no other solution, but note that there are many Spring classes internally that use these interfaces.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
I agree. Here's the link:
subject: Lifecycle of Spring Bean.
It's not a secret anymore!