Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading context in Spring using web.xml

Is there a way that a context can be loaded using web.xml in a Spring MVC application?

like image 251
Ganesh Avatar asked Jun 23 '11 08:06

Ganesh


People also ask

How do I add a context root in web xml?

To Set the Context RootA context root must start with a forward slash (/) and end with a string. In a packaged web module for deployment on the GlassFish Server, the context root is stored in glassfish-web. xml.

What is context xml in Spring?

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. Spring-servlet.

How application context is loaded in Spring?

Spring Boot finds the MyBean annotation and loads it into the application context bean factory. @Autowired private ApplicationContext applicationContext; With the @Autowired annotation we inject our ApplicationContext bean into the field. Now we can access the methods of the context.

How is ApplicationContext xml loaded?

Then you can use the WebApplicationContext to load the context: WebApplicationContext context = WebApplicationContextUtils. getRequiredWebApplicationContext(servlet.


2 Answers

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>     <param-name>contextConfigLocation</param-name>     <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param>  <listener>    <listener-class>         org.springframework.web.context.ContextLoaderListener    </listener-class> </listener>  

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); SomeBean someBean = (SomeBean) ctx.getBean("someBean"); 

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

like image 166
ddewaele Avatar answered Oct 03 '22 00:10

ddewaele


You can also specify context location relatively to current classpath, which may be preferable

<context-param>     <param-name>contextConfigLocation</param-name>     <param-value>classpath*:applicationContext*.xml</param-value> </context-param>  <listener>     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 
like image 25
fmucar Avatar answered Oct 03 '22 00:10

fmucar