Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Lifecycle of Spring Bean.

 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
Sid
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Mark

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic