最基础的SSM框架整合篇
一、简单理解
Spring、Spring MVC和MyBatis的整合主要原理就是将我们在单独使用Spring MVC和MyBatis过程中需要自己实例化的类都交由Ioc容器来管理,过程分为两步:
第一步整合Spring和Spring MVC,前提是项目已单独配置Spring和Spring MVC且能正常运行,主要步骤为先在项目中创建对应的service接口和它们的实现类,并通过注解实现类和在Spring配置文件中开启注解扫描的方式将接口实现类交由Ioc容器管理。接着在Controller响应请求的类中添加接口为成员变量,并且也通过注解的方式将其交由Ioc容器管理,最后,我们需要把Spring配置文件的加载设置为项目启动时,这里通过在web.xml文件中配置Spring监听器实现,至此就可以实现Spring和Spring MVC的整合。
第二整合Spring和MyBatis,前提也是项目已单独配置Spring和MyBatis且能正常运行,这里需要导入额外的jar包mybatis-spring.jar,这里的版本需要根据MyBatis版本来确认,且本项目通过c3p0来配置数据库连接池,也需要导入c3p0的jar包。主要步骤为先将MyBatis配置文件中的内容(配置连接池部分)转移到Spring配置文件中(原先的MyBatis配置文件也就可以删除了),并且在Spring配置文件中配置SqlSessionFactroy工厂和sql语句对应接口所在包,这也就是将工厂和接口都交由Ioc容器管理,至此就可以实现Spring和MyBatis的整合。
二、代码展示
1.配置文件
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_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>SSMProject</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 配置Spring监听器,默认加载WEB-INF目录下的applicationContext.xml配置文件 --> <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> <!-- 前端控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Spring MVC配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 表示容器在启动时立即加载dispatcherServlet --> <load-on-startup>1</load-on-startup> </servlet> <!-- 让Spring MVC控制器拦截前端所有请求 --> <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> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
applicationContext.xml(Spring配置文件)
<?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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 开启注解扫描,非controller --> <context:component-scan base-package="com.yh"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- Spring整合MyBatis --> <!-- 配置连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <!-- 驱动类名 --> <property name="jdbcUrl" value="jdbc:sqlserver://127.0.0.1:1433;databaseName=onlineshoppingmall" /><!-- url访问地址 --> <property name="user" value="sa" /><!-- 链接数据库的用户名 --> <property name="password" value="12345yehuan" /><!-- 链接数据库的密码 --> <property name="initialPoolSize" value="10" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <property name="maxIdleTime" value="0" /> </bean> <!-- 配置SqlSessionFactroy工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置接口所在包 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.yh.mybatis.mapper"></property> </bean> <!-- 配置Spring框架声明式事务管理 --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP增强 --> <aop:config> <aop:pointcut expression="execution(* com.yh.service.*.*(..))" id="txPoint"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> </beans>
springmvc.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:aop="http://www.springframework.org/schema/aop" 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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 开启注解扫描,只扫描controller注解 --> <context:component-scan base-package="com.yh.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 视图解析器对象 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="" /> <property name="suffix" value=".jsp" /> <property name="order" value="1" /> </bean> <!-- 解决访问html等其他资源404 --> <mvc:default-servlet-handler /> <!-- 开启SpringMVC注解支持 --> <mvc:annotation-driven /> </beans>
2.service接口和它的实现类
AddressService.java
package com.yh.service; import java.util.List; import com.yh.entity.Address; public interface AddressService { int addAddress(Address address); List<Address> loadAddress(); }
AddressServiceImpl.java
package com.yh.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yh.entity.Address; import com.yh.mybatis.mapper.AddressMapper; import com.yh.service.AddressService; @Service("addressService") public class AddressServiceImpl implements AddressService { @Autowired private AddressMapper am; @Override public int addAddress(Address address) { return am.addAddress(address); } @Override public List<Address> loadAddress() { System.out.println("业务层查找地址信息"); return am.loadAddress(); } }
3.MyBatis的sql语句配置文件和接口
AddressMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.yh.mybatis.mapper.AddressMapper"> <select id="loadAddress" resultType="com.yh.entity.Address"> select* from address </select> <insert id="addAddress" parameterType="com.yh.entity.Address"> insert into address (buyerid,consignee)values(#{buyerId},#{consignee}) </insert> </mapper>
AddressMapper.java
package com.yh.mybatis.mapper; import java.util.List; import org.springframework.stereotype.Repository; import com.yh.entity.Address; @Repository public interface AddressMapper { int addAddress(Address address); List<Address> loadAddress(); }
4.响应前端请求的Controller类
AddressController.java
package com.yh.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.yh.entity.Address; import com.yh.service.AddressService; @Controller @RequestMapping(value = "/address") public class AddressController { @Autowired private AddressService addressService; @ResponseBody @RequestMapping(value = "/loadAddress", produces = "application/json; charset=utf-8") public String loadAddress() { System.out.println("表现层查询所有地址"); Address addr = new Address(); addr.setBuyerId(99); addr.setConsignee("叶欢"); int result = addressService.addAddress(addr); System.out.println(result != 0 ? "成功" : "失败"); return null; } }
5实体类
Address.java
package com.yh.entity; import java.io.Serializable; public class Address implements Serializable { /** * */ private static final long serialVersionUID = 1L;
private int buyerId; private String consignee;public int getBuyerId() { return buyerId; } public void setBuyerId(int buyerId) { this.buyerId = buyerId; } public String getConsignee() { return consignee; } public void setConsignee(String consignee) { this.consignee = consignee; } @Override public String toString() { return "Address [addressId=" + addressId + ", buyerId=" + buyerId + ", consignee=" + consignee + ", telephone=" + telephone + ", detail=" + detail + ", defaultAddress=" + defaultAddress + "]"; } }