Monday, 18 September 2017

How to use ApplicationContextAware and BeanNameAware interfaces ?


In some situation, you may want to get the reference of Spring ApplicationContext (which is initialized once) somewhere in bean.

GET APPLICATIONCONTEXT REFERENCE IN THE BEAN
1. Implement interface ApplicationContextAware in your bean.
2. Define a member variable of type ApplicationContext
3. Override setApplicationContext method in your bean



EXAMPLE : ApplicationContextAware
public class Triangle implements ApplicationContextAware {
  ...
  ApplicationContext context = null;
  ...
  @override
  public void setApplicationContext(ApplicationContext context) 

         throws BeansException {
    this.context = context;
  }
}


Similarly, You can implement interfaces like, ApplicationEventPublisherAware, BeanClassloaderAware, BeanNameAware etc.


EXAMPLE : BeanNameAware
public class Triangle implements BeanNameAware {
  ...
  @override
  public void setBeanName(String beanName) {
    System.out.println("Bean name :" + beanName);
  }
}

It prints bean name on initialization of the bean.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.