文章目录
三、SSM框架整合
3.1 回顾三大框架
3.1.1 MyBatis环境
-
需要引入Mybatis依赖
-
编写MyBatisConfig.xml核心配置文件,配置连接信息、加载mapper文件、别名配置等等
-
需要编写Mapper.xml和Mapper接口、使用namespace关联,方法名和标签名一致,注意resultType、parameterType等;
3.1.2 Spring环境
- 1)Spring相关依赖
- 2)编写application.xml核心配置文件,编写相关配置(扫包、配置数据源、JdbcTempalte等JavaBean等)
- 3)使用注解配置Bean;@Controller、@Service、@Repository、@Competent等
- 4)配置aop切面、配置aop事务等;指事务管理器使用、 @Transacational 注解代替xml配置aop事务
3.1.3 SpringMVC环境
- 1)引入SpringMVC相关依赖;
- 2)编写dispatcher-servlet.xml核心配置文件
- 3)配置包扫描(Controller)、开启注解驱动、放行静态资源、视图解析器、拦截器等
3.2 搭建环境
3.2.1 搭建MyBatis环境
- 准备SQL:
drop table if exists `account`;
CREATE TABLE `account` (
`id` int(11) primary key auto_increment,
`username` varchar(255) ,
`money` double
) ENGINE = InnoDB ;
INSERT INTO `account` VALUES (1, 'xiaohui',1000);
INSERT INTO `account` VALUES (2, 'xiaolan',1000);
- 1)引入依赖:
<?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>com.dfbz</groupId>
<artifactId>SpringMVC_04_SSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--MyBatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--Junit测试单元-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
- 2)实体类:
package com.dfbz.entity;
import lombok.Data;
/**
* @author lscl
* @version 1.0
* @intro:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
private Integer id;
private String username;
private Double money;
}
- 3)编写dao接口:
package com.dfbz.mapper;
import com.dfbz.entity.Account;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
public interface AccountMapper {
List<Account> findAll();
}
4)编写AccountMapper.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">
<!--namespace 名称空间,指定对哪个接口进行映射-->
<mapper namespace="com.dfbz.mapper.AccountMapper">
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
- 5)jdbc.properties:
jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql:///test?characterEncoding=utf8&serverTimezone=GMT%2b8
jdbc.driverClassName=com.mysql.jdbc.Driver
6)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>
<!--加载jdbc.properties-->
<properties resource="jdbc.properties"/>
<!--日志配置-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--别名配置-->
<typeAliases>
<package name="com.dfbz.entity"/>
</typeAliases>
<!--环境配置-->
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<mappers>
<!--包扫描-->
<package name="com.dfbz.mapper"/>
</mappers>
</configuration>
- 7)测试类:
package com.dfbz.demo;
import com.dfbz.entity.Account;
import com.dfbz.mapper.AccountMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
public class Demo01 {
@Test
public void test1() throws Exception{
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
// 获取Session
SqlSession session = factory.openSession();
// 获取Mapper
AccountMapper accountMapper = session.getMapper(AccountMapper.class);
List<Account> userList = accountMapper.findAll();
for (Account account : userList) {
System.out.println(account);
}
session.close();
}
}
3.2.2 Spring整合MyBatis环境
Spring整合MyBatis的核心就是把MyBatis的核心配置文件(MyBatisConfig.xml)给去除
我们回想一下MyBatis的核心配置文件中都配了什么?
- 别名
- 数据源配置
- 加载mapper文件
- 引入Spring相关依赖:
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--MyBatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--Junit测试单元-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
<!--mybatis整合spring依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!--jdbc包(事务管理器在这里)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!--spring事务包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!--aop包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
- jdbc.properties:
jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql://localhost:3306/mybatis01?characterEncoding=UTF8
jdbc.driver=com.mysql.jdbc.Driver
- 编写application.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--包扫描-->
<context:component-scan base-package="com.dfbz"/>
<!--加载数据库配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置druid数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
</bean>
<!--配置sqlSession工厂(是mybatis整合spring包下的)-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--引用数据源-->
<property name="dataSource" ref="dataSource"/>
<!--加载mybatis核心配置文件(一般省略)-->
<!-- <property name="configLocation" value="classpath:SqlMapConfig.xml" />-->
<!--包别名配置-->
<property name="typeAliasesPackage" value="com.dfbz.entity"/>
<!--加载所有的mapper文件(一般使用MapperScannerConfigurer扫描)-->
<!-- <property name="mapperLocations" value="classpath:/com/dfbz/mapper/*.xml" />-->
</bean>
<!--配置mapper包扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dfbz.mapper"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务-->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true" isolation="DEFAULT" propagation="REQUIRED"/>
<tx:method name="save*" read-only="false"/>
<tx:method name="transfer*" read-only="false"/>
</tx:attributes>
</tx:advice>
<!--配置aop事务-->
<aop:config>
<aop:pointcut id="myPoint" expression="execution(* com.dfbz.service..*(..))"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="myPoint"></aop:advisor>
</aop:config>
</beans>
- UserService:
package com.dfbz.service;
import com.dfbz.entity.Account;
import com.dfbz.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
@Service
public class AccountService {
@Autowired
private AccountMapper accountMapper;
public List<Account> findAll() {
return accountMapper.findAll();
}
/**
* 转账
*
* @param accountId
* @param toAccountId
* @param money
*/
public void transfer(Integer accountId, Integer toAccountId, Double money) {
// 余额增加
accountMapper.addMoney(toAccountId, money);
int i = 1 / 0; // 模拟异常
// 余额减少
accountMapper.subMoney(accountId, money);
}
}
- AccountMapper:
package com.dfbz.mapper;
import com.dfbz.entity.Account;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
public interface AccountMapper {
List<Account> findAll();
void addMoney(Integer toAccountId,Double money);
void subMoney(Integer accountId, Double money);
}
- AccountMapper.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">
<!--namespace 名称空间,指定对哪个接口进行映射-->
<mapper namespace="com.dfbz.mapper.AccountMapper">
<select id="findAll" resultType="com.dfbz.entity.Account">
select * from account
</select>
<update id="addMoney">
update account set money=money+#{arg1} where id=#{arg0}
</update>
<update id="subMoney">
update account set money=money-#{param2} where id=#{param1}
</update>
</mapper>
- 测试类:
package com.dfbz.demo;
import com.dfbz.entity.Account;
import com.dfbz.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:application.xml")
public class Demo02 {
@Autowired
private AccountService accountService;
@Test
public void test1() throws Exception{
List<Account> accountList = accountService.findAll();
for (Account account : accountList) {
System.out.println(account);
}
}
@Test
public void test2() throws Exception{
accountService.transfer(1,2,100.0D);
}
}
3.2.3 整合SpringMVC
Spring和SpringMVC可以说是天然整合在一起的,不用任何整合,因为我们的所有IOC装配代码都可以写在SpringMVC的配置文件里面,包括扫包,装配Bean,配置事务,切面,AOP等等…
但我们项目开发中,为了分工明确,会把Spring和SpringMVC区分开来;
- SpringMVC负责处理Controller相关组件,包括我们自己编写的控制器,视图解析器,请求映射,文件上传,转换器等…
- Spring则负责业务上的组件,如Service,Dao,配置事务,数据源,AOP,以及一些其他相关的服务;
这样一来项目启动后将会创建两个容器,一个是Spring的IOC容器,一个是SpringMVC的IOC容器;
- 引入SpringMVC相关依赖:
<!--SpringMVC相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- json 转换工具 SpringMVC底层依赖的转换工具-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
- 编写web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--配置一个监听器,让Spring的IOC容器随着容器启动而初始化-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<!--spring核心(前端控制器)-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置springmvc配置文件的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name> <!--拦截除jsp之外所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping> <!--处理中文乱码过滤器-->
<filter>
<filter-name>characterEncoding</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>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- spring.xml(修改扫描的包):
<!--包扫描-->
<context:component-scan base-package="com.dfbz" >
<!--配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
Tips:Controller组件都交给SpringMVC扫描
- 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:mvc="http://www.springframework.org/schema/mvc"
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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--
只扫描com.dfbz下面的Controller组件
use-default-filters: 关闭默认的扫描规则(默认情况下会扫描)
-->
<context:component-scan base-package="com.dfbz" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置静态资源放行-->
<mvc:default-servlet-handler/>
<!--配置springmvc注解驱动-->
<mvc:annotation-driven/>
</beans>
- AccountController:
package com.dfbz.controller;
import com.dfbz.entity.Account;
import com.dfbz.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@GetMapping
public List<Account> findAll() {
return accountService.findAll();
}
@GetMapping("/transfer")
public String transfer() {
accountService.transfer(1, 2, 100.0D);
return "ok";
}
}
访问:
http://localhost:8080/account
http://localhost:8080/account/transfer
3.3 Spring与SpringMVC的父子容器
当Spring与SpringMVC整合成功后,将会有两个容器存在。其中Spring容器为父容器,SpringMVC的为子容器;
其关系为:子容器可以访问父容器中的组件,但父容器不可以访问子容器的组件;
- 测试:在AccountService中装配AccountController:
@Service
public class AccountService {
@Autowired
private AccountMapper accountMapper;
@Autowired
private AccountController accountController; // 访问父容器中的组件
}
启动服务器后出现错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.dfbz.controller.AccountController' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1717)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1273)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 62 more
3.4 import标签
SSM环境整合需要导入两个配置文件,一个是spring环境的配置文件另一个是springmvc环境的配置文件;
我加载两种环境的配置步骤如下:
- 1)加载spring配置文件:采用
ContextLoaderListener
监听器来监听服务器启动创建加载spring配置文件; - 2)加载SpringMVC配置文件:在
DispatcherServlet
中配置springmvc的配置文件路径,让其加载;
加载Spring环境的配置文件我们也可以采用导入的方式:
- 注释web.xml中关于加载Spring配置文件的代码:
<!--配置一个监听器,让Spring的IOC容器随着容器启动而初始化-->
<!--
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!–配置spring的配置文件–>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
-->
- 在SpringMVC的配置文件中导入其他的配置文件:
<!--导入其他配置文件-->
<import resource="classpath:application.xml" />
注意:使用import标签导入配置后,将不存在子父容器的关系了,所有的组件都被装配在一个IOC容器中;
再次测试在AccountService中装配AccountController:
@Service
public class AccountService {
@Autowired
private AccountMapper accountMapper;
@Autowired
private AccountController accountController; // 访问父容器中的组件
}
启动服务器,发现可以正常访问;
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/131647.html