How can we get access to ApplicationContext from a CommandLineRunner class. Is there a better newer way than using ApplicationContextAware
To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface.
Spring Boot injects the application context into the parameter of the setApplicationContext() method, where we get the Id of the Spring application. (The Id here is the name of the application.) In the Application , we create a bean, call its method and set up the Spring Boot application.
Applicationcontext. xml - It is standard spring context file which contains all beans and the configuration that are common among all the servlets. It is optional file in case of web app. Spring uses ContextLoaderListener to load this file in case of web application.
Here, BeanFactory is the root interface for accessing the Spring container. It provides basic functionalities for managing beans. On the other hand, the ApplicationContext is a sub-interface of the BeanFactory. Therefore, it offers all the functionalities of BeanFactory.
Autowiring would work, either as a field
@Autowired
private ApplicationContext context;
or a method
@Autowired
public void context(ApplicationContext context) { this.context = context; }
Same as ApplicationContextAware
really.
It's a smell in any case - maybe if you think about your use case you will find a way to do it without the context?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With