Saturday 11 April 2020

Java Spring MVC beans loading twice Solution


Java Spring MVC beans loading twice with below Solution we can make load it once.


1. Spring MVC Configuration(Web.xml).


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

In Above Web.xml Spring configuration we have to observe/change the below things.

1. The servlet "sampleapp" will load "applicationContext.xml/sampleapp-servlet.xml" file.
2. And the listener ContextLoaderListener will loads "sampleapp-servlet.xml" again.


To fix the above issues do the below changes in web.xml

Fix: 1. change the servet-name "sampleapp" to some other name.
2. change the "applicationContext.xml" to "projectname-servlet.xml", 
i.e: "javapages" is my project name.

Please find the below spring configuration web.xml after above changes.

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


No comments:

Post a Comment