SpringBoot 简介
Spring Boot
是由 Pivotal
团队提供的一套开源框架,可以简化 Spring
应用的创建及部署。它提供了丰富的 Spring
模块化支持,可以帮助开发者更轻松快捷地构建出企业级应用。Spring Boot
通过自动配置功能,降低了复杂性,同时支持基于 JVM
的多种开源框架,可以缩短开发时间,使开发更加简单和高效。
Spring Boot
官网地址 Getting Started | Building an Application with Spring Boot
Spring Boot
官方文档地址 Index of /spring-boot/docs/2.2.6.RELEASE/reference
父项目的创建
创建一个 Maven
项目,pom.xml
中实现版本的管理,标识是一个Spring Boot
项目。
xml
<!--标志是 springboot 的项目-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/>
</parent>
<properties>
<junit.version>4.12</junit.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<!--springboot-web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.2</version>
</dependency>
<!--mybatis-spring-boot-starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>
</dependencyManagement>
创建一个子项目
IDEA
基本配置,配置目录结构
配置项目名和目录名一致
配置Maven
依赖路径
配置 jdk
环境
pom.xml
文件中不需要加入版本了,父项目和子项目的关联自动生成,没有的需要自己手动添加。 编写主启动类,配置包扫描的路径
@SpringBootApplication
是 Spring Boot
的组合注解,标识这个类值项目的主启动类。主要目的是开启自动配置。
注解的源码如下
java
package org.springframework.boot.autoconfigure;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
@AliasFor(annotation = Configuration.class)
boolean proxyBeanMethods() default true;
}
@ComponentScan
1、开发者可以通过basePakage
等属性来细粒度的定制@ComponentScan
自动扫描的范围
2、如果不指定,则默认Spring
框架实现会从声明@ComponentScan
所在类的package
进行扫描。这就是Spring Boot
的启动类为什么最好放在root package
包下面的原因
@SpringBootConfiguration
此注解继承了@Configuration
注解,功能基本一致,都标识了当前类是配置类,且会在当前类内声明一个或多个以@Bean
注解标记的方法实例纳入到Spring
容器中。并且实例方法就是方法名。
注解的源码如下
java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
@AliasFor(annotation = Configuration.class)
boolean proxyBeanMethods() default true;
}
@Configuration
@Configuration
注释类表明其主要目的是作为bean
定义的源,继承了 @Component
注解类 @Configuration
类允许通过调用同一类中的其他@Bean
方法来定义bean
之间的依赖关系
注解的源码如下
less
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(annotation = Component.class)
String value() default "";
boolean proxyBeanMethods() default true;
}
@Component
注解
标注Spring
管理的Bean
,使用@Component
注解在一个类上,表示将此类标记为Spring
容器中的一个Bean
less
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
@MapperScan("com.best.mapper")
mapper
包扫描的注解,扫描mapper
层接口
SpringApplication.run(ApplicationClient.class,args);
run
方法主要作用是
1、创建一个SpringApplication
对象,对象初始化时保存事件监听器,容器初始化类以及判断是否为web
应用,保存包含main
方法的主配置类。
2、利用创建好的对象执行run()
准备spring
的上下文,完成容器的初始化,创建,加载等。会在不同的时机触发监听器的不同事件。下面是这个对象调用方法的源码
java
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class<?>[] { primarySource }, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
Spring Boot
项目的主启动类
java
@SpringBootApplication
@MapperScan("com.best.mapper")
public class ApplicationClient {
public static void main(String[] args) {
SpringApplication.run(ApplicationClient.class,args);
}
}
配置 application.yml
,配置端口号,配置mybatis
和数据源配置
yml
# server
server:
port: 80
# mybatis
mybatis:
configuration:
cache-enabled: true
map-underscore-to-camel-case: true
mapper-locations: classpath:mapper/*.xml
# spring
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/java?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
实体类,对应数据库的字段
@Data
辣椒插件注解,标识类上,生成一个类的get/set、toString
方法 @AllArgsConstructor
辣椒插件注解,标识在类上,生成类的有参构造 @NoArgsConstructor
辣椒插件注解,标识在类上,生成类的无参构造 @Accessors(chain = true)
辣椒插件注解,对象可链式写法
java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
}
mapper
接口编写,推荐 MybatisX
插件
@Mapper
标识这个是Dao
层接口的注解,mybatis
可以扫描到这个接口
java
@Mapper
public interface UserMapper {
List<User> list();
}
service
接口
java
public interface UserService {
List<User> list();
}
service
接口实现类
@Service
标识这个实现类是业务层接口实现类
java
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> list() {
return userMapper.list();
}
}
mapper
的xml
文件 编写 SQL
语句的文件
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">
<mapper namespace="com.best.mapper.UserMapper">
<select id="list" resultType="com.best.entity.User">
select *
from user;
</select>
</mapper>
控制器类
@RestController
复合注解标识了这个类是控制器,所有的方法默认由@ResponseBody
注解修饰
源码如下
java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(annotation = Controller.class)
String value() default "";
}
@RequestMapping("/user")
标识请求的路径
@ResponseBody
将java
对象转为json
格式的数据
java
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public ResponseData<List<User>> list() {
log.info("查询全部 >>> {} ", userService.list());
return ResponseData.success("成功", userService.list());
}
/**
* 需要返回一个 JSON 型的对象
*/
@ResponseBody
@GetMapping("/list2")
public List<User> list2() {
System.out.println(userService.list());
return userService.list();
}
}
数据库 ibd 文件备份
ibd
文件是数据库建表时候生成的一个二进制文件,描述了表的结构和数据,文件还有与表头结构关联
mysql
开启远程服务,可通过本机的ip
实现远程连接
SQL
mysql> use mysql;
Database changed
mysql> select host from user where user = 'root';
+-----------+
| host |
+-----------+
| localhost |
+-----------+
1 row in set (0.00 sec)
mysql> update user set host = '%' where user = 'root';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select host from user where user = 'root';
+------+
| host |
+------+
| % |
+------+
1 row in set (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
MySQL
查看 idb
表存储位置
SQL
mysql> show variables like '%datadir%';
+---------------+---------------------------------------------+
| Variable_name | Value |
+---------------+---------------------------------------------+
| datadir | C:\ProgramData\MySQL\MySQL Server 8.0\Data\ |
+---------------+---------------------------------------------+
1 row in set, 1 warning (0.00 sec)
MySQL
备份
SQL
cd /d C:\ProgramData\MySQL\MySQL Server 8.0\Data\java
ibd2sdi --dump-file back.txt user.ibd
会生成一个 back.txt 文件存储 user 的信息
mysql> alter table user discard tablespace;
Query OK, 0 rows affected (0.02 sec)
mysql> show tables;
+----------------+
| Tables_in_java |
+----------------+
| user |
| user_copy1 |
| user_copy2 |
| user_copy3 |
+----------------+
4 rows in set (0.01 sec)
但是文件没有了
mysql> alter table user import tablespace;
Query OK, 0 rows affected, 2 warnings (0.05 sec)
恢复文件
mysql> select * from user;
+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
+--------+----------+----------+
3 rows in set (0.00 sec)
mysql> insert into user(userid,username,password) values (4,"a","a");
Query OK, 1 row affected (0.01 sec)
mysql> select * from user;
+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | a | a |
+--------+----------+----------+
4 rows in set (0.00 sec)
MySQL
的转储
SQL
存储数据库文件
..\Data\java>mysqldump -u root -p java > dump.sql
Enter password: ******
拷贝数据库文件到 B 服务器
B 服务器中创建对应的数据库
create database java;
导入数据库文件到数据库中
..\Data\test>mysql -u root -p java < dump.sql
Enter password: ******
查看存储
C:\ProgramData\MySQL\MySQL Server 8.0\Data\test>mysql -u root -p
Enter password: ******
mysql> use java;
Database changed
mysql> show tables;
+----------------+
| Tables_in_java |
+----------------+
| user |
| user_copy1 |
| user_copy2 |
| user_copy3 |
+----------------+
4 rows in set (0.00 sec)
mysql> select * from user;
+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | a | a |
| 5 | a | a |
+--------+----------+----------+
5 rows in set (0.00 sec)
mysql> insert into user (userid,username,password) values (6,"s","s");
Query OK, 1 row affected (0.01 sec)
mysql> select * from user;
+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | a | a |
| 5 | a | a |
| 6 | s | s |
+--------+----------+----------+
6 rows in set (0.00 sec)
两台服务器通过ibd文件导入
SQL
A 机的数据库文件 ibd 文件导出传到 B 机上
B 机在数据库中创建和 ibd 表相同的表结构定义即可,插入一条数据
CREATE TABLE `user` (
`userid` int NOT NULL,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户密码',
PRIMARY KEY (`userid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
INSERT INTO `user` VALUES (4, 'a', 'a');
B 机 清除表空间
alter table user discard tablespace;
此时数据库中有表但是 Data 目录下没有 ibd 文件,但是数据库表无法查看
导入表空间后,A 机的表可用,可以添加数据
alter table user import tablespace;
INSERT INTO `user` VALUES (2, 'a', 'a');
数据库创建表的总结
所有的数据库表的设计添加 id
自增,tablename_id,create_time,update_time
属性
阿里巴巴编程规范一定要看