搭建一個基於spring+hibernate的maven管理項目(二)

搭建一個基於spring+hibernate的maven管理項目(二)

                                                ——集成spring

一、引入jar包依賴

在pom.xml中引入spring依賴

        <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.0.RELEASE</version>
		</dependency>

二、在web.xml配置啓動參數

	<!-- 配置spring mvc前端控制器 -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 隨着應用服務器啓動而初始化 若不配置,則第一次請求後完成初始化 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:zbox-*.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<!-- springmvc的映射規則: 可以配置:/、/xxx/*、*.* 不可配置:/* 與應用服務器配置默認衝突 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

三、編寫spring.xml文件

在web.xml文件中我們配置 默認加載 classpath下前綴爲zbox-的xml文件,所以名稱需要寫爲zbox-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	<!-- 添加cotroller掃描 -->
	<context:component-scan base-package="com.hao.**.service" />
	<context:component-scan base-package="com.hao.**.controller" />
	<context:component-scan base-package="com.hao.**.support" />
</beans>

這裏的配置 爲掃描com.hao下 所有結尾爲service和controller和support的包

四、測試編寫一個controller試試

訪問 http://localhost:8041/demo/homes/home 後臺輸出了1  說明配置完成  spring集成成功

總結,集成spring其實挺簡單的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章