Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting application context from a CommandLinerRunner

Tags:

spring-boot

How can we get access to ApplicationContext from a CommandLineRunner class. Is there a better newer way than using ApplicationContextAware

like image 801
adeelmahmood Avatar asked Jan 24 '14 23:01

adeelmahmood


People also ask

How do I find application context?

To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface.

How Spring boot creates the application context?

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.

What is application context XML?

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.

Is application context a bean?

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.


1 Answers

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?

like image 103
Dave Syer Avatar answered Sep 22 '22 08:09

Dave Syer