Spring ApplicationContext

ApplicationContext is one of the most important interface in a spring application.
It is responsible for initializing and configuring the beans in a spring application, and can be used to access those beans.
Following are some of the important features of ApplicationContext:
1. It manages the lifecycle of beans, including instantiation, initialization, and destruction.
2. It provides a way to publish and handle events within the Spring application.
3. It is responsible for initializing and configuring the beans in spring application and also for injecting beans into another beans.

In this article, we will understand different ways in which you can access Spring ApplicationContext in your classes.

1. Using ApplicationContextAware
A class can implement the ApplicationContextAware interface to get access to the ApplicationContext object.
This interface contains a setApplicationContext() method which accepts ApplicationContext as argument.
This argument is auto injected with current application context. Example,

@Component
public class AppBean implements ApplicationContextAware {
  private ApplicationContext context;

  @Override
  public void setApplicationContext(ApplicationContext c) {
    this.context = c;
  }
}

Remember that setApplicationContext() method will be invoked automatically, when the bean is initialized.
2. Autowiring
Simply define a variable of type ApplicationContext in a bean and annotate it with @Autowired annotation.
This will allow spring to inject its instance in the autowired field. Example,

@Component
public class AppBean {
  @Autowired
  private ApplicationContext context;
}

Once you have an object of ApplicationContext, you can use it get registered beans using their class names as shown below

MyBean myBean = applicationContext.getBean(MyBean.class);
myBean.doSomething();
Hope the article was useful.