ssm整合的簡單案例(有源碼)
ssm框架的整合可以採用多種方式,這裏選擇xml + 註解的方式,整合的前提是每一個部分都要能自己獨立運行,不然就沒有意義了。
整合思路如下圖:
一、先搭建整合環境
1.使用maven創建一個web項目
2.在pom.xml中導入相關座標
如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ssmzhenghe</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssmzhenghe Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring-->
<!--AOP相關技術-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<!--AOPjar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--context容器-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mvc相關jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--單元測試-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--事務-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--JDBC技術-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--單元測試-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>compile</scope>
</dependency>
<!--Mysql驅動jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--Servlet相關jar包-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!--頁面 el、jstl表達式-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log strat-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<!-- log end-->
<!--Mybatis相關jar包組件-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--spring整合mybatis所需jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--數據庫連接池:c3p0-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>ssmzhenghe</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
3.創建java文件夾與resource文件夾
二、先把spring配置搭建完
1.編寫applicationContext.xml文件
值得一提的是,spring只處理業務層與持久層的註釋,所以編寫掃描時,要把表現層controller排除
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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 開啓註解掃描 只需要處理service和dao -->
<context:component-scan base-package="ssm.test">
<!-- 配置哪些註解不掃描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
測試spring是否配置成功
service的實現類
package ssm.test.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssm.test.dao.AccountDao;
import ssm.test.domain.Account;
import ssm.test.service.AccountService;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public List<Account> findAll() {
System.out.println("業務層:查詢所有。。。");
return accountDao.findAll();
}
public void saveAccount(Account account) {
System.out.println("業務層:保存用戶。。,");
accountDao.saveAccount(account);
}
@Override
public void Delete(Integer id) {
System.out.println("業務層:刪除賬戶。。。");
accountDao.Delete(id);
}
}
測試類:
package ssm.test.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ssm.test.service.AccountService;
public class testSpring {
@Test
public void run1(){
//加載配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//獲取對象
AccountService as = (AccountService) ac.getBean("accountService");
//調用方法
as.findAll();
}
}
結果:
說明spring框架可以使用,測試通過
三、再使用spring整合springMVC框架
1.編寫web.xml,配置前端控制器 、解決中文亂碼
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加載springMVC.xml配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 啓動服務器,創建該Servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解決中文亂碼 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.編寫springmvc.xml文件,開啓註解掃描,只掃描Controller註解、配置視圖解析器、過濾靜態資源
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- 開啓註解掃描,只掃描Controller註解-->
<context:component-scan base-package="ssm.test">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置視圖解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 過濾靜態資源 -->
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 開啓springMVC註解支持 -->
<mvc:annotation-driven/>
</beans>
3.測試springMVC是否搭好
由於內容和代碼比較多,我就不寫上去了,最下面有我整個案例的源碼的鏈接,可以自行下載
如圖,spring環境搭好
4.spring整合springMVC框架
思路:spring整合springMVC:啓動Tomcat服務器的時候,需要加載spring的配置文件,來完成正常的依賴注入
具體實現,在web.xml中加入spring監聽器
<!-- 配置spring的監聽器,默認只加載WEB-INF目錄下的配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 但是由於SpringConfig.xml配置文件不在WEB-INF目錄下,所以需要指定路徑-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
測試:
兩個一起出現說明整合成功
四、最後使用spring整合MyBatis框架
1.編寫MyBatis核心文件
SqlMapConfig.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>
<!--引入外部配置文件-->
<!-- <properties resource="jdbcConfig.properties"></properties>-->
<!--使用typeAliases配置別名,它只能配置domain中的類名-->
<typeAliases>
<!--用於指定要配置別名的包,當指定之後,該包下的實體類都會註冊別名,並且類名就是別名,不再區分大小寫-->
<package name="ssm.test.domain"/>
</typeAliases>
<!--配置環境 -->
<environments default="mysql">
<!--配置mysql的環境-->
<environment id="mysql">
<!--配置事物類型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置數據源(連接池)-->
<dataSource type="POOLED">
<!--配置數據庫的基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件指的是每個dao獨立的配置文件-->
<mappers>
<!-- <mapper resource="com/qa/dao/UserDao.xml"/>-->
<!-- package標籤是用於指定dao接口所在的包,當指定了之後就不需要在寫mapper以及resource或者class了 -->
<package name="ssm.test.dao"></package>
</mappers>
</configuration>
2.編寫Dao接口
關於數據庫和實體類我沒有給出,但是可以在最下面我在GitHub的源碼下載整個案例
package ssm.test.dao;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import ssm.test.domain.Account;
import java.util.List;
/*
* 賬戶Dao接口
* */
public interface AccountDao {
//查詢所有
@Select("select * from account")
public List<Account> findAll();
//保存賬戶
@Insert("insert into account (name,money) values (#{name},#{money})")
public void saveAccount(Account account);
//刪除賬戶
@Delete("delete from account where id = #{id}")
public void Delete(Integer id);
}
3.測試MyBatis是否配置成功
如圖,測試成功
4.spring整合MyBatis框架
1)applicationContext.xml 追加一下配置
<!--Spring整合Mybatis框架-->
<!--配置連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--配置SqLSessionFactory工廠-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置AccountDao接口所在包-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="ssm.test.dao"></property>
</bean>
<!-- 配置spring框架聲明式事務管理 -->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事務通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP增強 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution( * ssm.test.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
2)把Dao給spring管理
在接口那裏加上@Repository
/*
* 賬戶Dao接口
* */
@Repository
public interface AccountDao {
//查詢所有
@Select("select * from account")
public List<Account> findAll();
//保存賬戶
@Insert("insert into account (name,money) values (#{name},#{money})")
public void saveAccount(Account account);
//刪除賬戶
@Delete("delete from account where id = #{id}")
public void Delete(Integer id);
}
測試整合
業務層調用了持久層的接口,測試成功
最後,因爲剛接觸ssm,肯定有很多問題,希望大佬的指正。
附源碼地址: https://github.com/Try-your-best-to-do/ssm