SpringBoot简介
快速入门
1.新建SpringBoot项目
左上角File中新建project
选择Spring Initializr
上面的Server URL可以改为https://start.aliyun.com
用阿里云的镜像,速度更快。
Web ==> Spring Web ==> Create
2.创建并编写控制器类
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
3.启动服务器
直接运行Application类,不需要使用本地的 Tomcat
和 插件
4.使用Postman发送请求,进行测试
成功!!!
5.与Spring开发对比
-
坐标
Spring 程序中的坐标需要自己编写,而且坐标非常多
SpringBoot 程序中的坐标是我们在创建工程时进行勾选自动生成的
-
web3.0配置类
Spring 程序需要自己编写这个配置类。这个配置类大家之前编写过,肯定感觉很复杂
SpringBoot 程序不需要我们自己书写
-
配置类
Spring/SpringMVC 程序的配置类需要自己书写。而 SpringBoot 程序则不需要书写。
可以发现SpringBoot极大的简化了Spring的开发,完胜!
注意事项
基于idea开发SpringBoot程序需要确保联网且能够加载到程序框架结构
SpringBoot概述
pringBoot 是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程。
大家已经感受了 SpringBoot 程序,回过头看看 SpringBoot 主要作用是什么,就是简化 Spring 的搭建过程和开发过程。
原始 Spring 环境搭建和开发存在以下问题:
-
配置繁琐
-
依赖设置繁琐
SpringBoot 程序优点恰巧就是针对 Spring 的缺点
- 自动配置。这个是用来解决 Spring 程序配置繁琐的问题
- 起步依赖。这个是用来解决 Spring 程序依赖设置繁琐的问题
- 辅助功能(内置服务器,…)。我们在启动 SpringBoot 程序时既没有使用本地的 tomcat 也没有使用 tomcat 插件,而是使用 SpringBoot 内置的服务器。
1.起步依赖
创建SpringBoot项目的时候pom.xml文件中自动生成了很多包含starter的依赖,这些依赖就是起步依赖
2.程序启动
创建SpringBoot工程时,会自动生成一个Application类,通过这个引导类,我们可以启动web服务器。
@SpringBootApplication
public class Springboot01QuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot01QuickstartApplication.class, args);
}
}
-
SpringBoot 在创建项目时,采用jar的打包方式
-
SpringBoot 的引导类是项目的入口,运行 main 方法就可以启动项目
因为我们在 pom.xml 中配置了 spring-boot-starter-web 依赖,而该依赖通过前面的学习知道它依赖 tomcat ,所以运行 main 方法就可以使用 tomcat 启动咱们的工程。
3.切换web服务器
可以看到web服务器的配置位于spring-boot-starter-web中,默认使用的是tomcat,我们将其切换为jetty
我们可以通过Dependency Analyzer依赖分析器来查找tomcat,右键,点击Go to Maven Dependency来定位到tomcat依赖。
复制spring-boot-starter-tomcat 和 org.springframework.boot
到pom.xml中使用exclusion标签排除tomcat依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
引入 jetty
服务器。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
配置文件
配置文件格式
SpringBoot有三种配置文件
application.properties
application.yml
application.yaml
入门案例(以修改服务器端口号为例)
默认端口号为8080,我们想将其修改为80端口
application.properties
server.port=80
application.yml
server:
port: 80
application.yaml
server:
port: 80
注意:1.SpringBoot
程序的配置文件名必须是 application
2.这三种配置的优先级为:application.properties
> application.yml
> application.yaml
YAML
简介
YAML,即 YAML Ain’t a Markup Language(YAML 不是一种标记语言)的递归缩写。YAML 其实意思是 Yet Another Markup Language(仍是一种标记语言)。它主要强度这种语言是以数据为中心,而不是以标记为中心,而像 XML 语言就使用了大量的标记。
YAML 可读性高,易于理解,用来表达数据序列化的格式。它的语法和其他高级语言类似,还可以简单表达数组、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件。
YAML 配置文件后缀为.yml,例如application.yml。
优点:
-
容易阅读
yaml 类型的配置文件比 xml 类型的配置文件更容易阅读,结构更加清晰
-
容易与脚本语言交互
-
以数据为核心,重数据轻格式
yaml 更注重数据,而 xml 更注重格式
YAML 文件扩展名:
- .yml (主流)
- .yaml
上面两种后缀名都可以,以后使用更多的还是 yml 的。
yaml格式语法规则
- YAML 使用 Unicode 字符,也可使用 UTF-8 或 UTF-16。
- 数据结构采用键值对的形式,即
键名称: 值
,注意冒号后面要有空格。 - 数组中的每个元素单独一行,并以
-
开头,例如- 陈皮
。或使用方括号,元素用逗号隔开,例如["陈皮", "狗蛋"]
。注意短横杆和逗号后面都有空格。 - 散列表中的每个成员单独一行,使用键值对形式,例如
name: 陈皮
。或者使用大括号并用逗号分开,例如{"name": 陈皮, "age": 18}
。 - 字符串值一般不使用引号,必要时可使用,使用双引号表示字符串时,会转义字符串中的特殊字符(例如\n)。使用单引号时不会转义字符串中的特殊字符。
- 字母大小写敏感。
- 使用缩进表示层级关系,缩进使用空格不推荐使用 tab,因为在不同系统 tab 长度可能不一样。
- 缩进的空格数可以任意,只要相同层级的元素左对齐即可。
- 用连续三个连字号
---
划分多个文档块。还有选择性的连续三个点号...
表示文件结尾。 #
表示注释,可以出现在一行中的任何位置,单行注释。- 使用逗号和冒号时,后面都必须接一个空白字符。所以可以在字符串或数值中自由加入分隔符号(例如5,280或者http://www.wikipedia.org)而不需要使用引号。
注意:数据前面要加空格与冒号隔开
yaml配置文件数据读取
1.使用 @Value注解
- 使用
@Value("表达式")
注解可以从配合文件中读取数据,注解中用于读取属性名引用方式是:${一级属性名.二级属性名……}
- 例如:我们可以在
BookController
中使用@Value
注解读取配合文件数据,如下
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private Integer port;
@Value("${enterprise.subject[0]}")
private String subject_00;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(lesson);
System.out.println(port);
System.out.println(subject_00);
return "hello , spring boot!";
}
}
2.Environment对象
- 上面方式读取到的数据特别零散,SpringBoot 还可以使用 @Autowired 注解注入 Environment 对象的方式读取数据。这种方式 SpringBoot 会将配置文件中所有的数据封装到 Environment 对象中,如果需要使用哪个数据只需要通过调用 Environment 对象的 getProperty(String name) 方法获取。具体代码如下:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Environment env;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(env.getProperty("lesson"));
System.out.println(env.getProperty("enterprise.name"));
System.out.println(env.getProperty("enterprise.subject[0]"));
return "hello , spring boot!";
}
}
注意:这种方式,框架内容大量数据,而在开发中我们很少使用。
3.自定义对象(主流)
SpringBoot 还提供了将配置文件中的数据封装到我们自定义的实体类对象中的方式。具体操作如下:
-
将实体类 bean 的创建交给 Spring 管理。
在类上添加 @Component 注解
-
使用 @ConfigurationProperties 注解表示加载配置文件
在该注解中也可以使用 prefix 属性指定只加载指定前缀的数据
-
在 BookController 中进行注入,具体代码如下:
//Enterprise内容如下:
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private int age;
private String tel;
private String[] subject;
getter...
setter...
toString...
}
//BookController内容如下:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Enterprise enterprise;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(enterprise.getName());
System.out.println(enterprise.getAge());
System.out.println(enterprise.getSubject());
System.out.println(enterprise.getTel());
System.out.println(enterprise.getSubject()[0]);
return "hello , spring boot!";
}
}
注意:使用这种方式,实体类会有警告出现。
需要在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
多环境配置
1.yaml文件配置
在 application.yml
中使用 ---
来分割不同的配置,内容如下
#启用的配置
spring:
profiles:
active: dev #表示使用的是开发环境的配置
---
#开发
spring:
profiles: dev #给开发环境起的名字
server:
port: 80
---
#生产
spring:
profiles: pro #给生产环境起的名字
server:
port: 81
---
#测试
spring:
profiles: test #给测试环境起的名字
server:
port: 82
---
在高版本springboot中,可以用spring.config.activate.on-profile配置项来配置不同环境
#开发
spring:
config:
activate:
on-profile: dev
2.properties文件
properties 类型的配置文件配置多环境需要定义多个不同的配置文件
- application.properties用来设定启用的配置
spring.profiles.active=dev
- application-dev.properties 是开发环境的配置文件。我们在该文件中配置端口号为 80
server.port=80
- application-test.properties 是测试环境的配置文件。我们在该文件中配置端口号为 81
server.port=81
- application-pro.properties 是生产环境的配置文件。我们在该文件中配置端口号为 82
server.port=82
多环境命令行启动参数设置(测试)
完成springboot工程开发后,我们会将工程打包成jar
包,提交给测试人员进行测试。
如何打包?注意:在执行package之前,先执行clean,防止之前的错误影响打包
测试人员在cmd中通过java -jar来快速启动web服务器,进行测试。
java -jar xxx.jar --参数1 --参数2
通过–来设置参数
–-spring.profiles.active=test #环境
–-server.port=81 #指定web服务器端口号为81
注意事项
-
在执行package命令前执行一次clean命令,防止之前执行结果影响打包
-
文件编码问题可能导致打包失败,去setting->Editor->File Encoding将Project Encoding和Default encoding for properties files改为utf-8即可
-
命令行启动时设置的参数优先级大于配置文件
优先级:命令行中设置的配置项>在配置文件中配置的>默认配置
多环境开发兼容(maven和springboot兼容)必须会
当Maven与SpringBoot同时对多环境进行控制时,以Maven为主
添加插件,我们要对于源码中非java类的操作要求加载Maven对应的属性,解析${}
占位符
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>UTF-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
Maven中的多环境配置
<!--启用该环境-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<profiles>
<!--开发环境-->
<profile>
<id>dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<!--生产环境-->
<profile>
<id>pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
<!--启用该环境-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!--测试环境-->
<profile>
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
</profiles>
配置文件分类
SpringBoot 定义了配置文件不同的放置的位置;而放在不同位置的优先级时不同的。
SpringBoot 中4级配置文件放置位置:
- 1级:classpath:application.yml
- 在 resources 下创建的 application.yml 配置文件
- 2级:classpath:config/application.yml
- 在 resources 下创建一个名为 config 的目录,在该目录中创建 application.yml 配置文件
- 3级:file :application.yml
- 在 jar 包所在位置创建 application.yml 配置文件
- 4级:file :config/application.yml
- 在 jar 包所在位置创建 config 文件夹,在该文件夹下创建 application.yml 配置文件
- 作用:
- 1级与2级留做系统打包后设置通用属性
- 3级和4级用于系统开发阶段设置通用属性
级别越高,优先级越高
SpringBoot整合第三方技术
整合Junit
在test ==> java ==> 包 ==> Tests类中
使用@Autowired自动装备要测试的bean。
在@Test中调用实例化对象的方法,对该方法进行测试。
@SpringBootTest
注意事项
如果测试类在SpringBoot启动类的包或子包中,可以省略启动类的设置,也就是省略classes的设定。
整合MyBatis
1.创建模块时,选中MyBatis Framework与一个数据库管理系统(MySQL Driver)
2.设置数据源参数,整合MyBatis
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
- 如何使用其他数据库连接池?
以Druid为例
-
在pom.xml中导入druid坐标
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency>
-
在application.yml中用type属性设置数据库连接池的类型为druid
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
3.定义实体类与dao接口
给dao接口加上@Mapper
注解,让Mybatis能够识别到dao接口
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.在测试类中注入dao
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
s-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
### 3.定义实体类与dao接口
给dao接口加上`@Mapper`注解,让Mybatis能够识别到dao接口
```java
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.在测试类中注入dao
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}