1. 程式人生 > >spring和spirngmvc整合

spring和spirngmvc整合

<!--
需要進行 Spring 整合 SpringMVC 嗎 ?
還是否需要再加入 Spring 的 IOC 容器 ?
是否需要再 web.xml 檔案中配置啟動 Spring IOC 容器的 ContextLoaderListener ?

1. 需要: 通常情況下, 類似於資料來源, 事務, 整合其他框架都是放在 Spring 的配置檔案中(而不是放在 SpringMVC 的配置檔案中).
實際上放入 Spring 配置檔案對應的 IOC 容器中的還有 Service 和 Dao.
2. 不需要: 都放在 SpringMVC 的配置檔案中. 也可以分多個 Spring 的配置檔案, 然後使用 import 節點匯入其他的配置檔案
-->

<!--
問題: 若 Spring 的 IOC 容器和 SpringMVC 的 IOC 容器掃描的包有重合的部分, 就會導致有的 bean 會被建立 2 次.
解決:
1. 使 Spring 的 IOC 容器掃描的包和 SpringMVC 的 IOC 容器掃描的包沒有重合的部分.
2. 使用 exclude-filter 和 include-filter 子節點來規定只能掃描的註解
-->

<!--
SpringMVC 的 IOC 容器中的 bean 可以來引用 Spring IOC 容器中的 bean.
返回來呢 ? 反之則不行. Spring IOC 容器中的 bean 卻不能來引用 SpringMVC IOC 容器中的 bean!
-->

 

 

web.xml檔案

    <!-- 配置啟動 Spring IOC 容器的 Listener -->
    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param
> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>
springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

spring.xml

    <context:component-scan base-package="com">
        <context:exclude-filter type="annotation" 
            expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" 
            expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

    <!-- 配置資料來源, 整合其他框架, 事務等. -->

springmvc

<context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="annotation" 
            expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" 
            expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

    <!-- 配置檢視解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven></mvc:annotation-driven>