概述

Spring是什么想必大家都很熟悉了,就不再多描述了。使用了很久的Spring,是不是很多人连原理都还没有弄清楚呢?这个系列开始,将通过一个基于SSM的demo项目来了解Spring的工作原理。前边我们已经分析过MyBatis的原理和源码了,这里开始分析Spring的原理和源码,此后再补上SpringMVC和SpringBoot。
用IDEA搭建SSM项目----整合Spirng、SpringMVC
- 通过IDEA创建web项目

- 填写groupId和artifactId

- 目录设置
提交后的目录结构如下:

我们按springboot项目的习惯,增加java和resources目录,并设置Sources Root和Resources Root,创建包

- 开始引入相关依赖,在pom.xml中添加依赖
先来引入Spring的各类依赖,包括SpringMVC包
<!-- Spring相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring MVC相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
5.创建一个TestController类,如下
package com.zhlab.ssm.demo.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @ClassName TestController
* @Description //TestController
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2021/1/18 0018 下午 4:05
**/
@Controller
@RequestMapping("/")
public class TestController {
@GetMapping("/test")
public String test(){
System.out.println("this is a test demo !");
return "test";
}
}
因为返回视图,所以在WEB-INF下,我们创建一个jsp文件夹,添加test.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>test</title>
</head>
<body>
hello spring mvc
</body>
</html>
- 开始设置Spring相关配置信息
往WEB-INF下的web.xml中添加dispatcherServlet信息
<!-- springMVC核心配置 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--spingMVC的配置路径 如果是classspath:资源是在resources下面-->
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截设置 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
注意到上边的spring-mvc.xml,是spring的配置信息,在WEB-INF中创建一个spring-mvc.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 扫描controller(controller层注入) -->
<context:component-scan base-package="com.zhlab.ssm.demo.web.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven />
<!-- 内容协商管理器 -->
<!--1、首先检查路径扩展名
2、其次检查Parameter
3、检查Accept Header-->
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- 扩展名至mimeType的映射,即 /user.json => application/json -->
<property name="favorPathExtension" value="true"/>
<!-- 用于开启 /userinfo/123?format=json 的支持 -->
<property name="favorParameter" value="true"/>
<property name="parameterName" value="format"/>
<!-- 是否忽略Accept Header -->
<property name="ignoreAcceptHeader" value="false"/>
<property name="mediaTypes"> <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用 -->
<value>
json=application/json
xml=application/xml
html=text/html
</value>
</property>
<!-- 默认的content type -->
<property name="defaultContentType" value="text/html"/>
</bean>
<!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
<mvc:default-servlet-handler />
<!-- 静态资源映射 -->
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
<!-- 对模型视图添加前后缀 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
</beans>
-
部署
tomcat的安装这里就不说了,我本地是tomcat-9.0.37
打开右上角的配置添加:
image.png
修改Deployment,+ ->artifact:ssmDemo_war_exploded

启动项目


用IDEA搭建SSM项目----整合MyBatis
- 添加MyBatis相关依赖
<!-- MyBatis相关包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!--MySQL相关包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- Spring集成MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
添加其他相关依赖,如日志、json解析、数据库连接池等依赖包
<!--阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 日志相关包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<!-- json解析相关包 jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!-- JSP标准标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
- 使用mybatis-generator插件,在pom.xml中加入插件
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
<plugins>
※这里有个坑,不要加在<pluginManagement>标签下
然后在resources/generator目录下创建generatorConfig.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="mysqlgenerator" targetRuntime="MyBatis3">
<property name="autoDelimitKeywords" value="true"/>
<!--可以使用``包括字段名,避免字段名与sql保留字冲突报错-->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 自动生成toString方法 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 自动生成equals方法和hashcode方法 -->
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<!-- 非官方插件 https://github.com/itfsw/mybatis-generator-plugin -->
<!-- 查询单条数据插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/>
<!-- 查询结果选择性返回插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin"/>
<!-- Example Criteria 增强插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"/>
<!-- 数据Model属性对应Column获取插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!-- 逻辑删除插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin">
<!-- 这里配置的是全局逻辑删除列和逻辑删除值,当然在table中配置的值会覆盖该全局配置 -->
<!-- 逻辑删除列类型只能为数字、字符串或者布尔类型 -->
<property name="logicalDeleteColumn" value="deleted"/>
<!-- 逻辑删除-已删除值 -->
<property name="logicalDeleteValue" value="1"/>
<!-- 逻辑删除-未删除值 -->
<property name="logicalUnDeleteValue" value="0"/>
</plugin>
<commentGenerator>
<property name="suppressDate" value="true"/>
<!--<property name="suppressAllComments" value="true"/>-->
</commentGenerator>
<!--数据库连接信息-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&verifyServerCertificate=false&useSSL=false&nullCatalogMeansCurrent=true"
userId="root"
password="root"/>
<javaTypeResolver>
<property name="useJSR310Types" value="true"/>
</javaTypeResolver>
<!--代码生成目录-->
<javaModelGenerator targetPackage="com.zhlab.ssm.demo.web.model" targetProject="src/main/java"/>
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zhlab.ssm.demo.web.mapper"
targetProject="src/main/java"/>
<!--表名,有多少个写多少个-->
<table tableName="sys_admin_user" domainObjectName="SysAdminUser">
<generatedKey column="admin_user_id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
双击生成代码


- 在resources下新建jdbc.properties文件和spring-mybatis.xml
jdbc.properties
jdbc_driverClassName =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&verifyServerCertificate=false&useSSL=false&nullCatalogMeansCurrent=true"
jdbc_username=root
jdbc_password=root
spring-mybatis.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: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-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 3.配置数据源 ,使用alibaba-druid数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="${jdbc_driverClassName}"/>
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
<property name="initialSize" value="10"/>
<property name="minIdle" value="10"/>
<property name="maxActive" value="50"/>
<property name="maxWait" value="60000"/>
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<property name="filters" value="wall,stat" />
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:/mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 ,自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,只要Mapper接口类和Mapper映射文件对应起来就可以了-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zhlab.ssm.demo.web.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置基于注解的声明式事务 -->
<!-- enables scanning for @Transactional annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
- 在resources下新建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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<!-- 1.配置jdbc文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties"/>
</bean>
<!-- 2.扫描的包路径,这里不扫描被@Controller注解的类 --><!--使用<context:component-scan/> 可以不在配置<context:annotation-config/> -->
<context:component-scan base-package="com.zhlab.ssm.demo">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<import resource="classpath:spring-mybatis.xml" />
</beans>
- web.xml中引入spring相关配置,加入上面创建的applicationContext.xml路径:
<!-- 读取spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
- 弄完以上配置,开始写service接口,写一个SysAdminUserService接口和实现类
public interface SysAdminUserService {
List<SysAdminUser> selectAll(SysAdminUser user);
}
SysAdminUserServiceImpl.java
/**
* @ClassName SysAdminUserServiceImpl
* @Description //SysAdminUserServiceImpl
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2021/1/19 0019 上午 10:57
**/
@Service
public class SysAdminUserServiceImpl implements SysAdminUserService {
@Autowired
SysAdminUserMapper sysAdminUserMapper;
@Override
public List<SysAdminUser> selectAll(SysAdminUser user){
return sysAdminUserMapper.selectAll(user);
}
}
7.写一个测试接口,在之前的TestController里添加
@Autowired
SysAdminUserService sysAdminUserService;
@GetMapping("/userList")
@ResponseBody
public List<SysAdminUser> list(){
return sysAdminUserService.selectAll(new SysAdminUser());
}
- 打开postman,访问http://localhost:8080/ssmDemo_war_exploded/userList,结果如下:

- 也可以直接写一个main方法来调用bean,如下App.java:
/**
* @ClassName App
* @Description //App
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2021/1/19 0019 下午 3:02
**/
public class App {
public static void main(String[] args) throws ClassNotFoundException {
//XmlBeanFactory因为已经被废弃,这里使用了ClassPathXmlApplicationContext
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
SysAdminUserService s = (SysAdminUserService)context.getBean(SysAdminUserService.class);
List<SysAdminUser> list = s.selectAll(new SysAdminUser());
list.stream().forEach(System.out::println);
}
}
运行main方法,结果如下:

好了,SSM的demo示例就已经完成了。
demo代码已传gitee:
https://gitee.com/kaixinshow/my-batis-note
总结

在用SpringBoot做项目熟悉了之后,回过来弄SSM框架的项目应该是比较简单的,搭建方面的工作不再过多描述,我们的目的主要是聚焦在对Spring常用模块的原理以及源码进行分析。
网友评论