1 SpringBoot入门
1.1 SpringBoot简介
Spring Boot 是 Spring 家族中的一个全新的框架,它用来简化 Spring 应用程序的创建和
开发过程,也可以说 Spring Boot 能简化我们之前采用 SpringMVC + Spring + MyBatis 框架进行
开发的过程。
在以往我们采用 SpringMVC + Spring + MyBatis 框架进行开发的时候,搭建和整合三大框
架,我们需要做很多工作,比如配置 web.xml,配置 Spring,配置 MyBatis,并将它们整合在
一起等,而 Spring Boot 框架对此开发过程进行了革命性的颠覆,完全抛弃了繁琐的 xml 配
置过程,采用大量的默认配置简化我们的开发过程。
所以采用 Spring Boot 可以非常容易和快速地创建基于 Spring 框架的应用程序,它让编
码变简单了,配置变简单了,部署变简单了,监控变简单了。正因为 Spring Boot 它化繁为
简,让开发变得极其简单和快速,所以在业界备受关注。
1.2 Spring Boot 的特性
➢ 能够快速创建基于 Spring 的应用程序
➢ 能够直接使用 java main 方法启动内嵌的 Tomcat 服务器运行 Spring Boot 程序,不需
要部署 war 包文件
➢ 提供约定的 starter POM 来简化 Maven 配置,让 Maven 的配置变得简单
➢ 自动化配置,根据项目的 Maven 依赖配置,Spring boot 自动配置 Spring、Spring mvc
等
➢ 提供了程序的健康检查等功能
➢ 基本可以完全不使用 XML 配置文件,采用注解配置
1.3 SpringBoot四大核心
- 自动配置 针对许多Spring应用程序和常见的应用功能,SpringBoot自动提供相关配置
- 起步依赖 告诉SpringBoot需要什么功能,它就能引入需要的依赖库
- Actuator 让你能深入运行中的SpringBoot应用程序,一探SpringBoot程序的内部信息(接口检查)
- 命令行界面 主要针对Groovy语言使用
2 SpringBoot 入门案例
2.1 第一个 SpringBoot 项目
2.1.1 开发步骤
- 创建一个 Module ,选择类型为 Spring Initializr 快速构建
- 设置 GAV 坐标及 pom 配置信息
- 选择 Spring Boot 版本及依赖
- 设置模块名称、Content Root 路径及模块文件的目录
2.1.2 入门案例
- 创建项目
- 运行Application.java文件的main方法
2.2 pom.xml文件
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>
<!--继承 SpringBoot 框架的一个父项目,所有自己开发的 Spring Boot 都必须的继承-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--当前项目的 GAV 坐标-->
<groupId>com.bjpowernode.springboot</groupId>
<artifactId>002-springboot-springmvc</artifactId>
<version>1.0.0</version>
<!--maven 项目名称,可以删除-->
<name>002-springboot-springmvc</name>
<!--maven 项目描述,可以删除-->
<description>Demo project for Spring Boot</description>
<!--maven 属性配置,可以在其它地方通过${}方式进行引用-->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--SpringBoot 框架 web 项目起步依赖,通过该依赖自动关联其它依赖,不需要我们一个一个去添加了
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--SpringBoot 框架的测试起步依赖,例如:junit 测试,如果不需要的话可以删除-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<!--SpringBoot 提供的打包编译等插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.3 入门案例分析
➢ Spring Boot 的父级依赖 spring-boot-starter-parent 配置之后,当前的项目就是 Spring
Boot 项目
➢ spring-boot-starter-parent 是一个 Springboot 的父级依赖,开发 SpringBoot 程序都需
要继承该父级项目,它用来提供相关的 Maven 默认依赖,使用它之后,常用的 jar
包依赖可以省去 version 配置
➢ Spring Boot 提供了哪些默认 jar 包的依赖,可查看该父级依赖的 pom 文件
➢ 如果不想使用某个默认的依赖版本,可以通过 pom.xml 文件的属性配置覆盖各个
依赖项,比如覆盖 Spring 版本
<spring-framework.version>5.0.0.RELEASE</ spring-framework.version >
➢ @SpringBootApplication 注解是 Spring Boot 项目的核心注解,主要作用是开启
Spring 自动配置在 ,如果在 Application 类上去掉该注解,那么不会启动 SpringBoot
程序
➢ main 方法是一个标准的 Java 程序的 main 方法,主要作用是作为项目启动运行的入
口
➢ @Controller 及 @ResponseBody 依然是我们之前的 Spring MVC,因为 Spring Boot
的里面依然是使用我们的 Spring MVC + Spring + MyBatis 等框架
2.4 Spring Boot 的核心配置文件
2.4 Spring Boot 的核心配置文件
2.4.1 核心配置格式
.properties
#设置内嵌 Tomcat 端口号
server.port=9090
#配置项目上下文根
server.servlet.context-path=/003-springboot-port-context-path
.yml 文件
yml 是一种 yaml 格式的配置文件,主要采用一定的空格、换行等格式排版进行配置。
yaml 是一种直观的能够被计算机识别的的数据序列化格式,容易被人类阅读,yaml 类
似于 xml,但是语法比 xml 简洁很多,值与前面的冒号配置项必须要有一个空格, yml 后
缀也可以使用 yaml 后缀
注意:当两种格式配置文件同时存在,使用的是.properties 配置文件.
2.4.2 多环境配置
在实际开发的过程中,我们的项目会经历很多的阶段(开发->测试->上线),每个阶段的配置也会不同,例如:端口、上下文根、数据库等,那么这个时候为了方便在不同的环境之间切换,SpringBoot 提供了多环境配置,具体步骤如下
-
为每个环境创建一个配置文件,命名必须以 application- 环境标识.properties|yml
application-dev.properties
#开发环境 #设置内嵌 Tomcat 默认端口号 server.port=8080 #设置项目的上下文根 server.servlet.context-path=/005-springboot-multi-environment-dev
application-product.properties
#生产环境 #配置内嵌 Tomcat 默认端口号 server.port=80 #配置项目上下文根 server.servlet.context-path=/005-springboot-multi-environment-product
application-test.properties
#测试环境 #配置内嵌 Tomcat 端口号 server.port=8081 #配置项目的上下文根 server.servlet.context-path=/005-springboot-multi-environment-test
在总配置文件 application.properties 进行环境的激活
#SpringBoot 的总配置文件 #激活开发环境 spring.profiles.active=dev #激活测试环境 spring.profiles.active=test #激活生产环境 spring.profiles.active=product
-
为每个环境创建一个配置文件,命名必须以 application- 环境标识.properties|yml
SpringBoot 总配置文件:application.yml
#springboot 总配置文件
# 激活开发环境
#spring:
# profiles:
# active: dev
# 激活测试环境
#spring:
# profiles:
# active: test
# 激活生产环境
spring:
profiles:
active: product
开发环境配置文件:application-dev.yml
# 设置开发环境配置
server:
port: 8080 # 设置 Tomcat 内嵌端口号
servlet:
context-path: /dev # 设置上下文根
测试环境配置文件:application-test.yml
# 设置测试环境配置
server:
port: 9090
servlet:
context-path: /test
生产环境配置文件:application-product.yml
# 设置生产环境配置
server:
port: 80
servlet:
context-path: /product
2.4.3 Spring Boot 自定义配置
在 SpringBoot 的核心配置文件中,除了使用内置的配置项之外,我们还可以在自定义配
置,然后采用如下注解去读取配置的属性值
2.4.3.1 @Value
application.yml 格式配置文件
# 设置端口号及上下文根
server:
port: 9090
servlet:
context-path: /
school:
name: ssm
websit: http://www.baidu.com
测试方法
@Controller
public class Test1 {
@Value("${school.name}")
private String schoolName;
@Value("${websit}")
private String websit;
@RequestMapping(value = "/springBoot/say2")
public @ResponseBody String say2() {
return schoolName + "------" + websit;
}
}
网址输入:http://127.0.0.1:9090/springBoot/say2
2.4.3.2 @ConfigurationProperties
将整个文件映射成一个对象,用于自定义配置项比较多的情况
定义一个新的类,并加上注解@Component,@ConfigurationProperties(prefix = “school”)
ConfigurationProperties 注解中添加属性 prefix,作用可以区分同名配置
@Component
@ConfigurationProperties(prefix = "school")
public class ConfigInfo {
private String name;
private String websit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsit() {
return websit;
}
public void setWebsit(String websit) {
this.websit = websit;
}
}
application.yml 格式配置文件
server:
port: 9090
servlet:
context-path: /
school:
name: ABC
websit: http://www.baidu.com
在 tController 中注入 ConfigInfo 配置类,测试方法
public class Test1 {
@Autowired
private ConfigInfo configInfo;
@RequestMapping(value = "/springBoot/say3")
public @ResponseBody String say3() {
return configInfo.getName() + "=======" + configInfo.getWebsit();
}
}
2.4.3.3 警告解决
在 ConfigInfo 类中使用了 ConfigurationProperties 注解后,IDEA 会出现一个警告,不影响程序的执行,open document,添加依赖到pom.xml即可。
2.4.3.4 中文乱码
由于配置文件出现中文导致乱码,可以先转化为 ASCII 码
2.5 SpringBoot前端使用jsp
3 Spring Boot 框架 Web 开发
3.1 Spring Boot 集成 MyBatis
添加mybatis依赖,MySQL驱动
使用MyBatis提供的逆向工程生成实体bean,映射文件,DAO接口
3.1.1 新建数据库
drop table if exists t_student;
create table t_student
(
id int(10) not null auto_increment,
name varchar(20) null,
age int(10) null,
constraint PK_T_STUDENT primary key clustered (id)
);
insert into t_student(name,age) values("zhangsan",25);
insert into t_student(name,age) values("lisi",28);
insert into t_student(name,age) values("wangwu",23);
insert into t_student(name,age) values("Tom",21);
insert into t_student(name,age) values("Jck",55);
insert into t_student(name,age) values("Lucy",27);
insert into t_student(name,age) values("zhaoliu",75);
3.1.2 实现步骤
在新建springboot项目之后,向pom.xml添加依赖
<!--MySQL 的驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!--MyBatis 整合 SpringBoot 的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
在 Springboot 的核心配置文件 application.yml 中配置数据源
server:
port: 9090
servlet:
context-path: /config
school:
name: ABC
websit: http://www.baidu.com
websit: http://www.baidu.com
mybatis.mapper-locations: classpath:com/vashon/springboot/mapper/*.xml
#配置数据库的连接信息
#注意这里的驱动类有变化
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboottest?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
username: root
password: 123456
开发代码,开发Bean和Dao,mapper.xml文件,可以用easyCode,也可以用Springboot下Mybatis反向工程生成。
创建controller
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/springBoot/student")
public @ResponseBody Object student() {
Student student = studentService.queryStudentById(1);
return student;
}
}
创建service及实现类
public interface StudentService {
Student queryStudentById(Integer id);
}
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
}
为mapper文件添加@Mapper
@Mapper
public interface StudentMapper {}
如果编译软件编译不了xml,添加以下信息
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
其他开发方式
-
在运行的主类 上添加注解释包扫描@MapperScan(“com.abc.springboot.mapper”),这样mapper就不用添加@Mapper注解
@SpringBootApplication @MapperScan("com.abc.springboot.mapper") public class Application {}
-
在 resources 目录下新建目录 mapper 存放映射文件,将 StudentMapper.xml 文件移到 resources/mapper 目录下
这需要在yml文件中配置路径
# 指定 Mybatis 映射文件的路径
mybatis.mapper-locations: classpath:mapper/*.xml
关于Mapper映射文件存放的位置的写法有以下两种:
-
将Mapper接口和Mapper映射文件存放到src/main/java同一目录下,还需要在pom文件中手动指定资源文件夹路径resources
-
将Mapper接口和Mapper映射文件分开存放
Mapper接口类存放到src/main/java目录下
Mapper映射文件存放到resources(类路径)
在springboot核心配置文件中指定mapper映射文件存放的位置
3.2 事务支持
1.在入口类中使用注解 @EnableTransactionManagement 开启事务支持(这一步可以省略)
@SpringBootApplication
@EnableTransactionManagement
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
2.在访问数据库的 Service 方法上添加注解 @Transactional 即可
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
@Transactional
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
}
————————————————
版权声明:本文为CSDN博主「Vashon_Lee」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_41618135/article/details/111714452