There are many way to get application context in Spring application. Those are given bellow:
1. **Via ApplicationContextAware**:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here `setApplicationContext(ApplicationContext applicationContext)` method you will get the applicationContext
> **ApplicationContextAware**:
> Interface to be implemented by any object that wishes to be notified
> of the ApplicationContext that it runs in. Implementing this interface
> makes sense for example when an object requires access to a set of
> collaborating beans.
2. **Via Autowired**:
@Autowired
private ApplicationContext applicationContext;
Here `@Autowired` keyword will provide the applicationContext. Autowired has some problem. It will create problem during unit-testing.
There are many way to get application context in Spring application. Those are given bellow:
1. **Via ApplicationContextAware**:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here `setApplicationContext(ApplicationContext applicationContext)` method you will get the applicationContext
2. **Via Autowired**:
@Autowired
private ApplicationContext applicationContext;
Here `@Autowired` keyword will provide the applicationContext.
For more info visit [this thread][1]
Thanks :)
[1]: https://stackoverflow.com/a/52850865/3073945