天天看點

全棧開發實戰|SSM 架構整合開發

作者:小滿隻想睡覺

01、相關 JAR 包

實作 SSM 架構整合開發,需要導入相關 JAR 包,包括 MyBatis、Spring、Spring MVC、MySQL 連接配接器、MyBatis 與 Spring 橋接器、Log4j 以及 DBCP 等 JAR 包。

1●MyBatis 架構所需的 JAR 包

MyBatis 架構所需的 JAR 包,包括它的核心包和依賴包。

2●Spring 架構所需的 JAR 包

Spring 架構所需的 JAR 包,包括它的核心子產品 JAR、AOP 開發使用的 JAR、JDBC 和事務的 JAR 包以及 Spring MVC 所需要的 JAR 包,具體如下:

commons-logging-1.2.jar

spring-aop-5.3.2.jar

spring-beans-5.3.2.jar

spring-context-5.3.2.jar

spring-core-5.3.2.jar

spring-expression-5.3.2.jar

spring-jdbc-5.3.2.jar

spring-tx-5.3.2.jar

spring-web-5.3.2.jar

spring-webmvc-5.3.2.jar

3●MyBatis 與 Spring 整合的中間 JAR 包

該中間 JAR 包的最新版本為 mybatis-spring-2.0.6.jar。此版本可從位址“http://mvnrepository.com/artifact/org.mybatis/mybatis-spring”下載下傳。

4●資料庫驅動 JAR 包

我們所使用的 MySQL 資料庫驅動包為 mysql-connector-java-5.1.45-bin.jar。

5●資料源所需的 JAR 包

整合時使用的是 DBCP 資料源,需要準備 DBCP 和連接配接池的 JAR 包。最新版本的 DBCP 的 JAR 包為 commons-dbcp2-2.8.0.jar,

可從位址“http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi”下載下傳;

最新版本的連接配接池的 JAR 包為 commons-pool2-2.9.0.jar,可從位址“http://commons.apache.org/proper/commons-pool/download_pool.cgi”下載下傳。

02、MapperScannerConfigurer 方式

一般情況下,将資料源及 MyBatis 工廠配置在 Spring 的配置檔案中,實作 MyBatis 與 Spring 的無縫整合。在 Spring 的配置檔案中,首先,使用 org.apache.commons.dbcp2.BasicDataSource 配置資料源。其次,使用 org.springframework.jdbc.datasource.DataSourceTransactionManager 為資料源添加事務管理器。最後,使用 org.mybatis.spring.SqlSessionFactoryBean 配置 MyBatis 工廠,同時指定資料源,并與 MyBatis 完美整合。

使用 Spring 管理 MyBatis 的資料操作接口的方式有多種。其中,最常用最簡捷的一種是基于 org.mybatis.spring.mapper.MapperScannerConfigurer 的整合,實作 Mapper 代理開發。MapperScannerConfigurer 将包()中所有接口自動裝配為 MyBatis 映射接口 Mapper 的實作類的執行個體(映射器),所有映射器都被自動注入 SqlSessionFactory 執行個體,同時掃描包中 SQL 映射檔案,MyBatis 核心配置檔案不再加載 SQL 映射檔案(但要保證接口與 SQL 映射檔案名相同)。配置檔案的示例代碼如下:

<!-- 配置資料源 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
  <property name="driverClassName" value="${jdbc.driver}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
  <!-- 最大連接配接數 -->
  <property name="maxTotal" value="${jdbc.maxTotal}" />
  <!-- 最大空閑連接配接數 -->
  <property name="maxIdle" value="${jdbc.maxIdle}" />
  <!-- 初始化連接配接數 -->
  <property name="initialSize" value="${jdbc.initialSize}" />
</bean>
<!-- 添加事務支援 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>
<!-- 開啟事務注解 -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- 配置MyBatis工廠,同時指定資料源,并與MyBatis完美整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <!-- configLocation的屬性值為MyBatis的核心配置檔案 -->
  <property name="configLocation" value="classpath:config/mybatis-config.xml" />
</bean>
<!--Mapper代理開發,MapperScannerConfigurer将包中所有接口自動裝配為MyBatis映射接口Mapper的實作類的執行個體(映射器),所有映射器都被自動注入SqlSessionFactory執行個體,同時掃描包中SQL映射檔案,MyBatis核心配置檔案不再加載SQL映射檔案 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <!-- mybatis-spring元件的掃描器,basePackage:屬性可以包含多個包名,多個包名之間可以用逗号或分号隔開 -->
  <property name="basePackage" value="dao" />
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>           

03、整合示例

下面通過 SSM 架構整合,實作【例 3-2】的功能。

【例 3-2】SSM 架構整合開發。

具體實作步驟如下。

1●建立 Web 應用并導入相關 JAR 包

使用 Eclipse 建立一個名為 ch3_2 的 Web 應用,将相關 JAR 包複制到 WEB-INF/lib 目錄中。

2●建立資料庫連接配接資訊屬性檔案及 Log4j 的日志配置檔案

在應用 ch3_2 的 src 目錄下,建立名為 config 的包,并在該包中建立資料庫連接配接資訊屬性檔案 jdbc.properties 檔案,具體内容如下:

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/springtest?characterEncoding=utf8

jdbc.username=root

jdbc.password=root

jdbc.maxTotal=30

jdbc.maxIdle=10

jdbc.initialSize=5

在應用 ch3_2 的 src 目錄下,建立 Log4j 的日志配置檔案 log4j.properties 檔案.

3●建立持久化類

在應用 ch3_2 的 src 目錄下,建立一個名為 com.mybatis.po 的包,并在該包中建立持久化類 MyUser。

4●建立 SQL 映射檔案

在應用 ch3_2 的 src 目錄下,建立一個名為 com.mybatis.mapper 的包,并在該包中建立 SQL 映射檔案 UserMapper.xml。

5●建立 MyBatis 的核心配置檔案

在應用 ch3_2 的 config 包中,建立 MyBatis 的核心配置檔案 mybatis-config.xml。在該檔案中,配置實體類别名、日志輸出等,具體内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <settings>
    <setting name="logImpl" value="LOG4J" />
  </settings>
  <typeAliases>
    <package name="com.mybatis.po" />
  </typeAliases>
</configuration>           

6●建立 Mapper 接口

在應用 ch3_2 的 com.mybatis.mapper 包中,建立接口 UserMapper。使用 @Repository 注解标注該接口是資料通路層。該接口中的方法與 SQL 映射檔案 UserMapper.xml 的 id 一緻。UserMapper 接口的核心代碼如下:

@Repository
public interface UserMapper {
  public MyUser selectUserById(Integer id);
  public List<MyUser> selectAllUser();
  public int addUser(MyUser myUser);
  public int updateUser(MyUser myUser);
  public int deleteUser(Integer id);
}           

7●建立控制類

在應用 ch3_2 的 src 目錄下,建立一個名為 controller 的包,并在該包中建立控制器類 TestController。在該控制器類中,調用 Mapper 接口中的方法操作資料庫,核心代碼如下:

@Controller
public class TestController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/test")
public String test() {
    //查詢一個使用者
    MyUser mu = userMapper.selectUserById(1);
    System.out.println(mu);
    //添加一個使用者
    MyUser addmu = new MyUser();
    addmu.setUname("陳恒");
    addmu.setUsex("男");
    userMapper.addUser(addmu);
    //修改一個使用者
    MyUser updatemu = new MyUser();
    updatemu.setUid(1);
    updatemu.setUname("張三");
    updatemu.setUsex("女");
    userMapper.updateUser(updatemu);
    //删除一個使用者
    userMapper.deleteUser(3);
    //查詢所有使用者
    List<MyUser> listMu = userMapper.selectAllUser();
    for (MyUser myUser : listMu) {
      System.out.println(myUser);
    }
    return "test";
  }
}           

8●建立測試頁面

在/WEB-INF/目錄下,建立一個名為 jsp 的檔案夾,并在該檔案夾中建立 test.jsp 檔案

9●建立 Web、Spring、Spring MVC 的配置檔案

在應用 ch3_2 的 config 包中建立 Spring 配置檔案 applicationContext.xml 和 Spring MVC 配置檔案 springmvc.xml,在應用 ch3_2 的/WEB-INF/目錄中建立 Web 配置檔案 web.xml。

在 Spring 配置檔案 applicationContext.xml 中,首先,使用加載資料庫連接配接資訊屬性檔案;其次,使用 org.apache.commons.dbcp2.BasicDataSource 配置資料源,并使用 org.springframework.jdbc.datasource.DataSourceTransactionManager 為資料源添加事務管理器;再次,使用 org.mybatis.spring.SqlSessionFactoryBean 配置 MyBatis 工廠,同時指定資料源,并與 MyBatis 完美整合;最後,使用 org.mybatis.spring.mapper.MapperScannerConfigurer 實作 Mapper 代理開發,将 basePackage 屬性指定包中所有接口自動裝配為 MyBatis 映射接口 Mapper 的實作類的執行個體(映射器),所有映射器都被自動注入 SqlSessionFactory 執行個體,同時掃描包中 SQL 映射檔案,MyBatis 核心配置檔案不再加載 SQL 映射檔案。Spring 配置檔案 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"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd
   http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 加載資料庫配置檔案 -->
  <context:property-placeholder location="classpath:config/db.properties" />
  <!-- 配置資料源 -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <!-- 最大連接配接數 -->
    <property name="maxTotal" value="${jdbc.maxTotal}" />
    <!-- 最大空閑連接配接數 -->
    <property name="maxIdle" value="${jdbc.maxIdle}" />
    <!-- 初始化連接配接數 -->
    <property name="initialSize" value="${jdbc.initialSize}" />
  </bean>
  <!-- 添加事務支援 -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <!-- 開啟事務注解 -->
  <tx:annotation-driven transaction-manager="txManager" />
  <!-- 配置MyBatis工廠,同時指定資料源,并與MyBatis完美整合 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:config/mybatis-config.xml" />
  </bean>
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.mybatis.mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
  </bean>
</beans>           

在 Spring MVC 配置檔案 springmvc.xml 中,使用掃描控制器包,并使用 org.springframework.web.servlet.view.InternalResourceViewResolver 配置視圖解析器。具體代碼如下:

<?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"
    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">
   <context:component-scan base-package="controller"/> 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            id="internalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/jsp/" />
       <property name="suffix" value=".jsp" />
    </bean>
</beans>           

在 Web 配置檔案 web.xml 中,首先通過加載 Spring 配置檔案 applicationContext.xml,并通過 org.springframework.web.context.ContextLoaderListener 啟動 Spring 容器;其次配置 Spring MVC DispatcherServlet,并加載 Spring MVC 配置檔案 springmvc.xml。Web 配置檔案 web.xml 的代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  id="WebApp_ID" version="4.0">
  <!-- 執行個體化ApplicationContext容器 -->
  <context-param>
    <!-- 加載applicationContext.xml檔案 -->
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:config/applicationContext.xml
      </param-value>
  </context-param>
  <!-- 指定以ContextLoaderListener方式啟動Spring容器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--配置Spring MVC DispatcherServlet -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!-- classpath是指到src目錄查找配置檔案 -->
      <param-value>classpath:config/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>
</web-app>           

10●測試應用

釋出應用 ch3_2 到 Web 伺服器 Tomcat 後,通過位址 http://localhost:8080/ch3_2/test 測試應用。成功運作後,控制台資訊輸出結果,如圖 3.4 所示。

全棧開發實戰|SSM 架構整合開發

image.png

04、SqlSessionDaoSupport 方式

在 MyBatis 中,當我們編寫好通路資料庫的映射器接口後,MapperScannerConfigurer 就能自動根據這些接口生成 DAO 對象,然後使用 @Autowired 把這些 DAO 對象注入到業務邏輯層或控制層。是以,在這種情況下的 DAO 層中,幾乎不用編寫代碼,而且也沒有地方編寫,因為隻有接口。這固然友善,不過當我們需要在 DAO 層寫代碼時,這種方式就無能為力。幸運的是,MyBatis-Spring 提供了繼承 SqlSessionDaoSupport 類的方式通路資料庫。

類 org.mybatis.spring.support.SqlSessionDaoSupport 繼承了 org.springframework.dao.support.DaoSupport 類,是一個抽象類,是作為 DAO 的基類使用,需要一個 SqlSessionFactory。我們在繼承 SqlSessionDaoSupport 類的子類中通過調用 SqlSessionDaoSupport 類的 getSqlSession()方法來擷取這個 SqlSessionFactory 提供的 SqlSessionTemplate 對象。而 SqlSessionTemplate 類實作了 SqlSession 接口,即可以進行資料庫通路。是以,我們需要 Spring 架構給 SqlSessionDaoSupport 類的子類的對象(多個 DAO 對象)注入一個 SqlSessionFactory。

但自 mybatis-spring-1.2.0 以來,SqlSessionDaoSupport 的 setSqlSessionTemplate 和 setSqlSessionFactory 兩個方法上的 @Autowired 注解被删除,這就意味着繼承于 SqlSessionDaoSupport 的 DAO 類,它們的對象不能被自動注入 SqlSessionFactory 或 SqlSessionTemplate 對象。如果在 Spring 的配置檔案中一個一個地配置的話,顯然太麻煩。比較好的解決辦法是在我們的 DAO 類中覆寫這兩個方法之一,并加上 @Autowired 或 @Resource 注解。那麼如果在每個 DAO 類中都這麼做的話,顯然很低效。更合理的做法是,寫一個繼承于 SqlSessionDaoSupport 的 BaseDao,在 BaseDao 中完成這個工作,然後其他的 DAO 類再都 BaseDao 繼承。BaseDao 的示例代碼如下:

package dao;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class BaseDao extends SqlSessionDaoSupport  {
   //依賴注入sqlSession工廠
   @Resource(name = "sqlSessionFactory")
   public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
         super.setSqlSessionFactory(sqlSessionFactory);
   }
}           

下面通過執行個體講解繼承 SqlSessionDaoSupport 類的方式通路資料庫。

【例 3-3】【例 3-2】的基礎上,實作繼承 SqlSessionDaoSupport 類的方式通路資料庫。

1●建立 Web 應用并導入相關 JAR 包

使用 Eclipse 建立一個名為 ch3_3 的 Web 應用,将相關 JAR 包複制到 WEB-INF/lib 目錄中。

2●複制資料庫連接配接資訊屬性檔案及 Log4j 的日志配置檔案

在應用 ch3_3 的 src 目錄下,建立名為 config 的包,将應用 ch3_3 的資料庫連接配接資訊屬性檔案 jdbc.properties 檔案複制到該包中。

将應用 ch3_2 的 Log4j 日志配置檔案 log4j.properties 檔案,複制到 ch3_3 的 src 目錄中,并将其中的“log4j.logger.com.mybatis.mapper=DEBUG”修改為“log4j.logger.dao=DEBUG”。

3●建立持久化類

在應用 ch3_3 的 src 目錄下,建立一個名為 po 的包,并在該包中建立持久化類 MyUser。

4●建立 SQL 映射檔案

在應用 ch3_3 的 src 目錄下,建立一個名為 dao 的包,并在該包中建立 SQL 映射檔案 UserMapper.xml。該檔案内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.UserMapper">
  <!-- 根據uid查詢一個使用者資訊 -->
  <select id="selectUserById" parameterType="Integer"  resultType="MyUser">
    select * from user where uid = #{uid}
  </select>
  <!-- 查詢所有使用者資訊 -->
  <select id="selectAllUser"  resultType="MyUser">
    select * from user
  </select>
</mapper>           

5●建立 MyBatis 的核心配置檔案

在應用 ch3_3 的 config 包中,建立 MyBatis 的核心配置檔案 mybatis-config.xml。在該檔案中,配置實體類别名、日志輸出、指定映射檔案位置等,具體内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <settings>
    <setting name="logImpl" value="LOG4J" />
  </settings>
  <typeAliases>
    <package name="po" />
  </typeAliases>
  <!-- 告訴 MyBatis到哪裡去找映射檔案 -->
   <mappers>
        <mapper resource="dao/UserMapper.xml"/>
   </mappers>
</configuration>           

6●建立 DAO 接口和接口實作類

在應用 ch3_3 的 dao 包中,建立接口 UserMapper。UserMapper 接口代碼如下:

package dao;
import java.util.List;
import po.MyUser;
public interface UserMapper {
   public MyUser selectUserById(int id);
   public List<MyUser> selectAllUser();
}           

在應用 ch3_3 的 dao 包中,建立 BaseMapper 類,在該類中使用 @Resource(name = "sqlSessionFactory")注解依賴注入 sqlSession 工廠。BaseMapper 類的核心代碼如下:

public class BaseMapper extends SqlSessionDaoSupport  {
   //依賴注入sqlSession工廠
   @Resource(name = "sqlSessionFactory")
   public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
         super.setSqlSessionFactory(sqlSessionFactory);
   }
}           

在應用 ch3_3 的 dao 包中,建立接口 UserMapper 的實作類 UserMapperImpl,在該類中使用 @Repository 注解标注該類的執行個體是資料通路對象。UserMapperImpl 類的核心代碼如下:

@Repository
public class UserMapperImpl extends BaseMapper implements UserMapper {
  public MyUser selectUserById(int id) {
    //擷取SqlSessionFactory提供的SqlSessionTemplate對象
    SqlSession session = getSqlSession();
    return session.selectOne("dao.UserMapper.selectUserById", id);
  }
  public List<MyUser> selectAllUser() {
    SqlSession session = getSqlSession();
    return session.selectList("dao.UserMapper.selectAllUser");
  }
}           

7●建立控制類

在應用 ch3_3 的 src 目錄下,建立一個名為 controller 的包,并在該包中建立控制器類 MyController。在該控制器類中,調用 UserMapper 接口中的方法操作資料庫,核心代碼如下:

@Controller
public class MyController {
  @Autowired
  private UserMapper userMapper;
  @RequestMapping("/test")
  public String test() {
    // 查詢一個使用者
    MyUser mu = userMapper.selectUserById(1);
    System.out.println(mu);
    // 查詢所有使用者
    List<MyUser> listMu = userMapper.selectAllUser();
    for (MyUser myUser : listMu) {
      System.out.println(myUser);
    }
    return "test";
  }
}           

8●建立測試頁面

在/WEB-INF/目錄下,建立一個名為 jsp 的檔案夾,并在該檔案夾中建立 test.jsp 檔案

9●建立 Web、Spring、Spring MVC 的配置檔案

在應用 ch3_3 的 config 包中建立 Spring 配置檔案 applicationContext.xml 和 Spring MVC 配置檔案 springmvc.xml,在應用 ch3_3 的/WEB-INF/目錄中建立 Web 配置檔案 web.xml。

在 Spring 配置檔案 applicationContext.xml 中,首先,使用加載資料庫連接配接資訊屬性檔案;其次,使用 org.apache.commons.dbcp2.BasicDataSource 配置資料源,并使用 org.springframework.jdbc.datasource.DataSourceTransactionManager 為資料源添加事務管理器;最後,使用 org.mybatis.spring.SqlSessionFactoryBean 配置 MyBatis 工廠,同時指定資料源,并與 MyBatis 完美整合。Spring 配置檔案 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"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd
   http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 加載資料庫配置檔案 -->
  <context:property-placeholder location="classpath:config/db.properties" />
  <!-- 配置資料源 -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <!-- 最大連接配接數 -->
    <property name="maxTotal" value="${jdbc.maxTotal}" />
    <!-- 最大空閑連接配接數 -->
    <property name="maxIdle" value="${jdbc.maxIdle}" />
    <!-- 初始化連接配接數 -->
    <property name="initialSize" value="${jdbc.initialSize}" />
  </bean>
  <!-- 添加事務支援 -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <!-- 開啟事務注解 -->
  <tx:annotation-driven transaction-manager="txManager" />
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:config/mybatis-config.xml"></property>
    </bean>
</beans>           

在 Spring MVC 配置檔案 springmvc.xml 中,使用掃描包,并使用 org.springframework.web.servlet.view.InternalResourceViewResolver 配置視圖解析器。具體代碼如下:

<?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"
    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">
    <context:component-scan base-package="controller"/> 
    <context:component-scan base-package="dao"/> 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            id="internalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/jsp/" />
       <property name="suffix" value=".jsp" />
    </bean> 
</beans>           

在 Web 配置檔案 web.xml 中,首先通過加載 Spring 配置檔案 applicationContext.xml,并通過 org.springframework.web.context.ContextLoaderListener 啟動 Spring 容器;其次配置 Spring MVC DispatcherServlet,并加載 Spring MVC 配置檔案 springmvc.xml。

10●測試應用

釋出應用 ch3_3 到 Web 伺服器 Tomcat 後,通過位址 http://localhost:8080/ch3_3/test 測試應用。

繼續閱讀