Loading context in Spring using web.xml

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

+63
java spring-mvc
Jun 23 2018-11-11T00:
source share
3 answers

From spring docs

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

<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> 

Then you can use WebApplicationContext to get the handle to beans.

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

Learn more about http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html

+112
Jun 23 '11 at 8:40
source share

You can also specify the context location relative to the current class path, 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> 
+34
Jun 23 '11 at 8:45
source share

You can also load context when defining the servlet itself ( WebApplicationContext )

  <servlet> <servlet-name>admin</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/*.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>admin</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> 

not ( ApplicationContext )

 <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> 

or can do both together.

The disadvantage of using WebApplicationContext is that it will only load the context for this particular Spring entry point ( DispatcherServlet ), where, as with the above methods, the context for multiple entry points will be loaded (e.g. Webservice Servlet, REST servlet , etc. .).

The context loaded by the ContextLoaderListener will be the parent context for the one that is specifically loaded for the DisplacherServlet. Thus, you can download all your business services, data access or beans repository in the context of the application and select your controller, view the beans converter in WebApplicationContext.

+13
Sep 27 '15 at 7:57
source share



All Articles