The first and foremost thing which is needed to implement a spring application is the entry for DispatcherServlet in the web.xml and we will write our Spring Configuration file (<servlet-name>-servlet.xml) which will also be placed in the WEB-INF folder. By default, Spring Framework will search for all the bean definition in an xml file with the name <servlet-name>-servlet.xml.
Let’s take a look at the below code
<servlet> <servlet-name>SpringConfig</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringConfig</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
There we have mentioned the <servlet-name> as SpringConfig and hence our Spring Context Configuration file should be named as “SpringConfig-servlet.xml”
So how to change the Spring Context Configuration file name to a custom one like “Config.xml”. We can add a below snippet called “contextConfigLocation” as an init-param to make this happen
<servlet> <servlet-name>SpringConfig</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/Config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringConfig</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
Now the contextConfigLocation parameter will override the “setContextConfigLocation” of the DispatcherServlet and hence our custom xml (Config.xml) will be called.
You can add multiple files as well just by separating with a comma.
<servlet> <servlet-name>SpringConfig</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/Config.xml,/WEB-INF/Test.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringConfig</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
Leave a Reply