Tuesday, 19 April 2016

How to Inject Application Context to a bean in Spring?

Some times, we need to access the Application Context in a bean itself, for example, if you want to get another bean using Application Context.

Injecting Application Context to a bean is easy, your bean just has to implement ApplicationContextAware interface,

ApplicationContextAware interface has a single method, which has the signature like below.
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // TODO Auto-generated method stub

  }
you have to override this method, see the example below
public class A implements ApplicationContextAware {

     private ApplicationContext context;

     public void setApplicationContext( ApplicationContext context)
     {
          this.context = context; 
     } 
}
That's it, now you can play with Application Context.

0 comments:

Post a Comment

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