新手入門java中Spring+SpringMVC+MyBatis框架整合詳細步驟
Springmvc+spring+mybatis環境搭建
注意:這裡我是用Spring的famerwork的參考文件聯合搭建
- 搭建spring環境
Spring的基本包+SpringMVC基本+MyBatis基本+mybatis-spring整合,增加tx包,aop包,c3p0,orm,jdbc
mybatis-spring整合包下載:
(1)在web.xml中新增監聽器
<!-- Spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> |
(2)在src下建立applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans> |
2、搭建SpringMVC環境
(1)在web.xml中建立DispatcherServlet
<servlet> <servlet-name>springmvc</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>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> |
(2)在Src下建立SpringMVC的配置檔案
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /> </beans> |
3、Spring接管資料庫配置
<!-- 配置資料庫 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <context:property-placeholder location="classpath:jdbc.properties" /> |
注意:新增context約束。
4、Spring接管SqlSessionFactory
可以參考MyBatis的案例:
<!-- 接管SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> |
7、開啟Spring事務管理
只要是整合了Spring,一般會將事務交給Spring來管理 ,
<!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 開啟事務掃描 --> <tx:annotation-driven /> |
我們可不再需要MyBatis的全域性配置檔案,所有的配置均可以在Spring接管,但是一般建議留下該全域性配置檔案,有一些settings之類配置可以放在裡面。
這時在SqlSessionFactory中新增一個property
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
8、開啟相關注解掃描
service
springmvc的controller等
springmvc檢視解析器
到這裡一個完整的ssm框架搭建就完成了!