Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the instances of the WebApplicationContext and DispatcherServlet in the spring-web-mvc at the runtime of an spring web application

i want to get the instance of the WebApplicationContext and the DispatcherServlet instance in the function under the controller class.

like image 321
Ranjit Swain Avatar asked Nov 08 '13 07:11

Ranjit Swain


People also ask

Where is DispatcherServlet defined in Spring MVC?

The DispatcherServlet is the front controller in Spring web applications. It's used to create web applications and REST services in Spring MVC. In a traditional Spring web application, this servlet is defined in the web. xml file.

Can we have 2 application context in Spring?

We can have multiple application contexts that share a parent-child relationship. A context hierarchy allows multiple child contexts to share beans which reside in the parent context. Each child context can override configuration inherited from the parent context.

Can we have more than one DispatcherServlet in Spring MVC?

Yes, a Spring MVC web application can have more than one DispatcherServlets. Each DispatcherServlet has to operate in its own namespace. It has to load its own ApplicationContext with mappings, handlers, etc. Only the root application context will be shared among these Servlets.

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

ApplicationContext is used to create standalone applications. WebApplicationContext is used to create web applications. ApplicationContext is the parent of the WebApplicationContext interface. WebApplicationContext is the child of the ApplicationContext interface.


1 Answers

As of Spring 2.5, you can get a reference to WebApplicationContext using @Autowired annotation:

@Autowired
WebApplicationContext applicationContext;

You can also obtain a reference of ApplicationContext by implementing ApplicationContextAware interface :

public class YourController implements ApplicationContextAware {
ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
...
}

But I don't think there is way to get a reference to the DispatcherServlet instance or to an instance of any Servlet present in your application. Earlier there was a way to obtain it using ServletContext.getServlet(), which is deprecated now.

like image 195
Debojit Saikia Avatar answered Oct 20 '22 22:10

Debojit Saikia