根据DispatchServlet使用ContextLoaderListener

Phư*_*yễn 5 java spring spring-mvc

我想使用ContextLoaderListener(以便我可以将Spring Beans传递给我的servlet)以及DispatchServlet(Spring MVC).但是,目前我必须将init param传递给这两个类初始值设定项:

<param-name>contextConfigLocation</param-name>
<param-value>
    /WEB-INF/spring/app-config.xml
</param-value>
Run Code Online (Sandbox Code Playgroud)

所以,我对这两个类使用相同的xml.不知道是否会导致我的bean被初始化两次?如果是,我该怎么做才能避免这种情况?

ska*_*man 12

对于两者ContextLoaderListenerDispatcherServlet,contextConfigLocation参数是可选的.

ContextLoaderListener默认为/WEB-INF/application.xml,DispatcherServlet默认为/WEB-INF/servletname-servlet.xml.

如果明确设置这些参数,则不应将它们设置为相同的值.在ContextLoaderListenerDispatcherServlet应该有套不同的bean定义背景,否则,就像你说的,豆类将两次实例化.


mok*_*ino 6

要强制DispatcherServlet初始化使用ContextLoaderListener中的上下文,您应将contextConfigLocation设置为空:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring-context.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)