SpringBoot 2.X 笔记 Published on Aug 9, 2025 in 日常 with 0 comment ### 1. SpringBoot 概念 SpringBoot 提供了一种快速使用 Spring 的方式,基于约定优于配置的思想,可以让开发人员不必在配置和逻辑业务之间进行思维的切换,从而大幅提升开发效率。 - 自动配置:SpringBoot 自动配置是一个运行时的过程,考虑了众多因素,是自动完成的。 - 起步依赖:将具备某种功能的坐标打包在一起,并提供一些默认的功能。 - 辅助功能:提供了一些大型项目常见的非功能特性,如嵌入式服务器、安全、指标、外部配置等。 - SpringBoot 并不是对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式。 ### 2. 快速入门 官方网站:https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/htmlsingle/#getting-started-installing-spring-boot #### 2.1 典型的 Maven pom ```xml 4.0.0 com.example myproject 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin ``` 编写 Controller,如下代码所示: ```java package org.alan.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "Hello World"; } } ``` #### 2.2 编写引导类,相当于 SpringBoot 的入口。 ```java package org.alan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HelloApplication { public static void main(String[] args){ SpringApplication.run(HelloApplication.class, args); } } ``` #### 2.3 运行与测试 现在点击运行,执行构建过程,可以在控制台看到以下内容:  此时,打开浏览器,输入 localhost:8080 ,可以看到如下输出:  #### 2.4 总结 - SpringBoot 在创建项目时,使用 jar 的打包方式。 - SprintBoot 的引导类是项目入口,使用 main 方法就可以启动项目。 - 使用 SpringBoot 和 Spring 构建的项目,业务代码的方式基本一致。 ### 3. SpringBoot 起步依赖 - 在 spring-boot-starter-parent 中定义了各种技术的版本信息,组合了一套最优搭配的技术版本。 - 在各种的 starter 中,定义了完成该功能需要的坐标合集,其中大部分版本信息来自于父工程。 ### 4. SpringBoot 配置 #### 4.1 配置文件分类 SpringBoot 是基于约定的,很多配置都有默认值。如果想使用自己的配置替换默认配置的话,就可以使用 application.properties 或者 application.yml(application.yaml)进行配置。 - properties: `server.port=8080` - yml: ```yaml server: port: 8080 ``` 其中,在 SpringBoot 中,同级目录下的 properties 目录的优先级最高,yml 优先级高于 yaml。 #### 4.2 YAML 语法 - 大小写敏感。 - 数据值前面必须有空格作为分隔符。 - 使用缩进表示层级关系。 - 缩进时不允许使用 TAB ,只允许空格。 - 缩进的空格数目不重要,相同层级对齐即可。 - 井号表示注释。 #### 4.3 YAML 数据格式 - 对象(map):键值对的集合。 ```yaml person: name: Jack person: {name: Jack} ``` - 数组:一组按次序排列的值 ```yaml address: - beijing - shandong address: [beijing,shandong] ``` - 纯量,单个的、不可再分的值 ```yaml msgA: 'hello \n world' #单引号忽略转义字符 msgB: "hello \n world" #双引号识别转义字符 ``` - 参数引用 ```yaml name: Jack person: name: ${name} #引用上方定义的 name 值 ``` #### 4.4 读取配置 ##### @Value (1)在 resources 中创建一个 application.yml 文件,指定端口为 8888,并自定义参数,如下所示: ```yaml name: Jack server: port: 8888 person: name: Jazmine age: 23 ``` (2)创建一个 controller 类,当访问 /init 时在控制台打印在 application.yml 中定义的参数 name 的值。 ```java package org.alan.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class InitController { @Value("${name}") private String name; @RequestMapping("/init") public void init(){ System.out.println("The name is " + name); } } ``` (3)编写引导类,启动项目。 ```java package org.alan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class InitApplication { public static void main(String[] args){ SpringApplication.run(InitApplication.class, args); } } ``` 运行之后,可以看到项目被运行到了 8888 端口,并在请求指定路径后,打印了 name 的值。  (4)也可以获取对象的值,在 @Value 中修改为 `@Value("${person.name}")`,重新运行项目可以发现输出变成了如下所示:  (5) 获取数组类型的值,在参数文件中增加一个数组类型的参数,如下所示: ```yaml name: Jack server: port: 8888 person: name: Jazmine age: 23 address: - beijing - shanghai - nantong ``` 然后在 Controller 中增加一个变量,并尝试打印出来: ```java @Value("${address[0]}") private String address; ```  ##### Environment 如下代码所示,通过 Env 导入参数: ```java package org.alan.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class InitController { @Autowired private Environment env; @RequestMapping("/init") public void init(){ System.out.println("The name is " + env.getProperty("name")); System.out.println("The address is " + env.getProperty("person.age")); } } ```  ##### @ConfigurationProperties (1)创建一个 Person 类: ```java package org.alan; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties public class Person { private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } ``` (2)此时,应当注入我们所需要的属性。因而,可以在 `@ConfigurationProperties` 注解中,增加` prefix` 参数,如下所示: ```java @ConfigurationProperties(prefix = "person") ``` (3)在 Controller 中注入 Person: ```java package org.alan.controller; import org.alan.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class InitController { @Autowired private Person person; @RequestMapping("/init") public String init(){ return person.toString(); } } ``` 效果如下所示:  #### 4.5 profile 多文件配置 在开发 SpringBoot 应用时,通常同一套程序会被安装到不同环境,比如开发 、测试、生产等。其中数据库地址、服务器端口等配置可能会有不同。如果每次打包都修改配置文件,操作会非常麻烦。Profile 功能就是用来进行动态配置切换的。 ##### 创建 dev 和 test 配置文件 (1) application-dev.properties `server.port = 8111` (2) application-test.properties `server.port = 8222` ##### 创建 properties 用于指定配置文件 `spring.profiles.active = dev` ##### 运行发现,已经切换到了指定的配置  #### 4.6 profile yml 多文档方式 ##### 编写 yml 文件 ```yaml --- server: port: 8881 spring: profiles: dev --- server: port: 8882 spring: profiles: test --- server: port: 8883 spring: profiles: pro --- ``` ##### 激活所需的配置 ```yaml spring: profiles: active: pro ``` ##### 验证效果  ### 5. 整合 Junit #### 5.1 实现步骤 - 搭建 SpringBoot 工程。 - 引入 starter-test 起步依赖。 - 编写测试类。 - 添加测试相关注解` @Runwith(SpringRunner.class)`、`@SpringBootTest(classes=启动类.clas)`。 - 编写测试方法。 #### 5.2 引入依赖 ```xml org.springframework.boot spring-boot-starter-test junit junit ``` #### 5.3 创建示例 Service 代码 ```java package org.alan.controller.service; import org.springframework.stereotype.Service; @Service public class UserService { public void hello(){ System.out.println("Hello"); } } ``` #### 5.4 编写测试类 在 test.java 包中,创建测试类: ```java package org.alan.service; import org.alan.TestApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * UserService 的测试类 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = TestApplication.class) public class UserServiceTest { @Autowired private UserService userService; @Test public void testService(){ userService.hello(); } } ``` #### 运行后的效果:  ### 6. 整合 mybatis #### 6.1 实现步骤 - 搭建 springboot 工程。 - 引入 mybatis 起步依赖,添加 mysql 驱动。 - 编写 DataSource 和 Mybatis 相关配置。 - 定义表和实体类。 - 编写 dao 和 mapper 文件 / 纯注解开发。 - 测试。 #### 6.2 引入 mybatis 相关依赖 ```xml 4.0.0 org.alan springboot-db 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test junit junit org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0 mysql mysql-connector-java ``` #### 6.3 创建一个测试库表 (1)创建 User 表: ```sql CREATE TABLE `User` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `username` VARCHAR(50) NOT NULL, `email` VARCHAR(100) NOT NULL, `password` VARCHAR(100) NOT NULL, `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP ); ``` (2)插入一些测试数据: ```sql INSERT INTO `User` (`username`, `email`, `password`) VALUES ('alice', 'alice@example.com', 'password1'), ('bob', 'bob@example.com', 'password2'), ('charlie', 'charlie@example.com', 'password3'), ('david', 'david@example.com', 'password4'), ('eve', 'eve@example.com', 'password5'), ('frank', 'frank@example.com', 'password6'), ('grace', 'grace@example.com', 'password7'), ('heidi', 'heidi@example.com', 'password8'), ('ivan', 'ivan@example.com', 'password9'), ('judy', 'judy@example.com', 'password10'), ('karen', 'karen@example.com', 'password11'), ('leo', 'leo@example.com', 'password12'), ('mallory', 'mallory@example.com', 'password13'), ('nancy', 'nancy@example.com', 'password14'), ('oliver', 'oliver@example.com', 'password15'), ('peggy', 'peggy@example.com', 'password16'), ('quinn', 'quinn@example.com', 'password17'), ('ruth', 'ruth@example.com', 'password18'), ('sybil', 'sybil@example.com', 'password19'), ('trent', 'trent@example.com', 'password20'); ```  #### 6.4 创建实体类 建立一个 domain 包,创建 User 类,参考数据库字段创建变量并设置相应的 setter 和 getter 方法: ```java package org.alan.domain; import java.sql.Time; import java.util.Date; public class User { private int id; private String username; private String password; private String email; private Date created_at; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreate_at() { return created_at; } public void setCreate_at(Date create_at) { this.created_at = create_at; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", create_at=" + created_at + '}'; } } ``` #### 6.5 编写配置信息 在 resources 中编写 application.yaml 文件,填入以下 datasource 信息。 ```java # datasource spring: datasource: url: jdbc:mysql:///springboot?serverTimezone=UTC username: root password: 123456 drive-class-name: com.mysql.jdbc.Driver ``` #### 6.6.1 结合注解创建 mapper 接口 可以通过注解实现对 User 表的查询,如下所示: ```java package org.alan.mapper; import org.alan.domain.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface Usermapper { @Select("select * from user") public List findAll(); } ``` #### 6.6.2 结合 XML 创建 mapper 接口 (1)在 mapper 种创建 UserXmlMapper 接口,如下所示: ```java package org.alan.mapper; import org.alan.domain.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface UserXmlmapper { public List findAll(); } ``` (2)在 resources / mapper 中编写 xml 文件,命名为 UserMapper.xml,其中 mybatis 头为固定写法,namespace 指定到刚才编写的 UserXmlMapper : ```xml select * from user ``` (3)修改 application.yaml 文件,增加 mybatis 相关配置: ```xml # datasource spring: datasource: url: jdbc:mysql:///springboot?serverTimezone=UTC username: root password: 123456 drive-class-name: com.mysql.jdbc.Driver # mybatis mybatis: mapper-locations: classpath:mapper/*Mapper.xml # mapper 的映射文件路径 type-aliases-package: org.alan.domain ``` 最后在测试类中测试,可以看到同注解方式的结果保持一致。 #### 6.7 创建测试类 ```java import org.alan.MybatisApplication; import org.alan.domain.User; import org.alan.mapper.Usermapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = MybatisApplication.class) public class MybatisApplicationTest { @Autowired private Usermapper usermapper; @Test public void queryAll(){ List list = usermapper.findAll(); for(User user : list){ System.out.println(user.toString()); } } } ``` 运行查看结果:  本文由 Alen 创作,采用 知识共享署名4.0 国际许可协议进行许可本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名最后编辑时间为: Aug 9, 2025 at 03:54 pm