一、入门
一、依赖
- 继承父工程spring-boot-starter-parent(必要)
- spring-boot-starter-web(必要)
- spring-boot-starter-test(可选)
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.miao</groupId>
<artifactId>SpringBoot-First-HelloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot-First-HelloWorld</name>
<description>SpringBoot-First-HelloWorld</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、起步
1. Controller层
package com.miao.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/demo1")
public String hello() {
return "<h1>Hello World! Spring Boot!</h1>";
}
}
2. 启动类
package com.miao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootFirstHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootFirstHelloWorldApplication.class, args);
}
}
运行启动类,访问http://localhost:8080/demo1即可。
三、配置文件
- 配置文件之间属性可以互补。
- 配置文件相同属性有优先级properties > yml > yaml
1. properties
server.port=8081
2. yml
server:
port: 8082
3. yaml(重要)
server:
port: 8083
1. 数据格式及使用
- 对象
# 写法一
person:
name: 张三
# 写法二
person: {name: 张三}
- 数组
# 写法一
address:
- 北京
- 上海
# 写法二
address: [北京, 上海]
- 常量
msg1: 'Hello \n World!' # 单引号忽略转义字符
msg2: "Hello \n World!" # 双引号识别转义字符
- 参数引用
name: 张飞
person:
name: ${name} # 该值为张飞
2. 读取数据(重要)
name: 张三
person:
name: 马超
age: 18
arr:
- 上海
- 北京
msg1: 'Hello \n World!' # 单引号忽略转义字符
msg2: "Hello \nWorld!" # 双引号识别转义字符
1. @Value
@Value("${name}")
private String name1;
@Value("${person.name}")
private String name2;
@Value(("${person.age}"))
private int age;
@Value("${arr[0]}")
private String address1;
@Value("${arr[1]}")
private String address2;
@Value("${msg1}")
private String msg1;
@Value("${msg2}")
private String msg2;
@RequestMapping("/data1")
public String data1() {
System.out.println(name1);
System.out.println(name2);
System.out.println(age);
System.out.println(address1);
System.out.println(address2);
System.out.println(msg1);
System.out.println(msg2);
return name1 + "----" + name2 + age + "----" +
address1 + address2 + "----" + msg1 +
"----" + msg2;
}
2. Environment
@Autowired
private Environment env;
@RequestMapping("/data2")
public String data2() {
System.out.println(env.getProperty("person.name"));
System.out.println(env.getProperty("person.age"));
return env.toString();
}
3. @ConfigurationProperties
- 需要加上spring-boot-configuration-processor,用来取消报错并且对配置文件有提示
package com.miao.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "person") // 对象前缀
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Autowired
private Person person;
@RequestMapping("/data3")
public String data3() {
System.out.println(person);
return person.toString();
}
4. profile(重要)
- 用来动态切换配置
1. 激活
- properties多文件方式。
- 编写application.properties、application-dev.properties、application-pro.properties、application-test.properties四个配置文件
1. application.properties:
spring.profiles.active=dev // 填写为后缀,即dev、pro和test
2. application-dev.properties:
server.port=8081
3. application-pro.properties:
server.port=8082
4. application-test.properties:
server.port=8083
- yml分部分方式
- 编写一个application.yml配置文件,用
---
来分割部分。
---
server:
port: 8088
spring:
config:
activate:
on-profile: dev
---
server:
port: 8089
spring:
config:
activate:
on-profile: pro
---
server:
port: 8090
spring:
config:
activate:
on-profile: test
---
# 选择激活的部分
spring:
profiles:
active: test
- 外部参数方式
VM options: -Dspring.profiles.active=xxx
,会覆盖配置文件对此处的配置。
- 命令行方式
Program arguments: --spring.profiles.active=xxx
会覆盖配置文件对此处的配置。
5. 项目配置文件加载
- 内部配置文件加载
- 当前项目(模块的父目录)的/config目录 > 当前项目(模块的父目录)的根目录 > classpath的/config目录(resources/config) > classpath的根目录(resources)
JavaSpringBoot1(当前项目)--
-JavaSpringBoot-First-HelloWorld -- src/
-- pom.xml
-JavaSpringBoot-Seconde-profile -- src/
-- pom.xml
- 外部配置文件加载
四、整合
一、Junit
1、依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
2、起步
package com.miao;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
// 该类若与启动类在同一目录或者在其子目录则可以不写classes
@SpringBootTest(classes = SpringBootThirdIntegrateApplication.class)
class SpringBootThirdIntegrateApplicationTests {
@Test
void contextLoads() {
System.out.println("Hello World!");
}
}
二、MyBatis
1、依赖
- 勾选mybatis framework和MySQL Driver
2、起步
1. 实体类User
package com.miao.pojo;
public class User {
private String name;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
2. 接口类UserMapper(XML/注解)
package com.miao.mapper;
import com.miao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper // 生成该接口的实现类并当成bean交给IOC容器管理
public interface UserMapper {
// @Select("SELECT * FROM t_test")
List<User> findAll();
}
3. aplication.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://101.43.117.227:3308/SSM
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志输出
mapper-locations: classpath:mapper/*Mapper.xml # 映射文件
type-aliases-package: com.miao.pojo # 实体类别名
4. 映射文件UserMapper.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.miao.mapper.UserMapper">
<select id="findAll" resultType="User">
SELECT * FROM t_test
</select>
</mapper>
5. 测试类
package com.miao;
import com.miao.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringBootFifthMyBatisIntegrateApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
System.out.println(userMapper.findAll());
}
}
三、Redis
1、依赖
- 勾选Spring Data Redis (Access+Driver)
2、起步
1. 配置文件
spring:
redis:
host: 101.43.117.227
port: 6380
2. 测试类
package com.miao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class SpringBootIntegrateRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// 存入数据
redisTemplate.boundValueOps("name").set("张三");
// 获取数据
System.out.printf("%s", (String) redisTemplate.boundValueOps("name").get());
}
}
五、原理
一、自动配置
一、注解
1. @Conditional/*
- 以下几个常用的注解都在org.springframework.boot.autoconfigure.condition中
1. @ConditionalOnClass/Bean
2. @ConditionalOnMissingClass/Bean
3. @ConditionalProperty
2. @Enable*
3. @Import
4. @EnableAutoConfiguration
二、 切换内置Web容器
1. 排除tomcat
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 1.排除默认对tomcat的依赖 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 2. 切换成jetty服务器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
三、自定义starter
六、监控
1. 接口类ApplicationContextInitializer
package com.miao.listener;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
}
}
2. 接口类SpringApplicationRunListener
package com.miao.listener;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import java.time.Duration;
public class MySpringApplicationRunListener implements SpringApplicationRunListener {
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
SpringApplicationRunListener.super.starting(bootstrapContext);
}
@Override
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
SpringApplicationRunListener.super.environmentPrepared(bootstrapContext, environment);
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
SpringApplicationRunListener.super.contextPrepared(context);
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
SpringApplicationRunListener.super.contextLoaded(context);
}
@Override
public void started(ConfigurableApplicationContext context, Duration timeTaken) {
SpringApplicationRunListener.super.started(context, timeTaken);
}
@Override
public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
SpringApplicationRunListener.super.ready(context, timeTaken);
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
SpringApplicationRunListener.super.failed(context, exception);
}
}
3. 接口类CommandLineRunner
package com.miao.listener;
import org.springframework.boot.CommandLineRunner;
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
}
}
4. 接口类ApplicationListener
package com.miao.listener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MyApplicationListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
}
}
5. Actuator监控
- 勾选Sping Boot Actuator
- 日志输出了
Exposing 1 endpoint(s) beneath base path '/actuator'
- 访问localhost:8080/actuator
info.name=user
info.age=18
# 开启健康检查完整信息
management.endpoint.health.show-details=always
# 将所有监控的endpoint暴露
management.endpoints.web.exposure.include=*
6. Admin图形化界面
- server勾选codecentric’s Spring Boot Admin(Server),client勾选codecentric’s Spring Boot Admin(Client)
- 以上两个依赖已经存在Sping Boot Actuator,故不用再勾选Sping Boot Actuator
- 需要server模块和client模块
1. server端
- 启动类
package com.miao;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAdminServer // 开启Admin服务端
public class SpringBootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminServerApplication.class, args);
}
}
- 配置文件
server.port=9000
2. client端
- 配置文件
# 执行admin.server地址
spring.boot.admin.client.url=http://localhost:9000
# 开启健康检查完整信息
management.endpoint.health.show-details=always
# 将所有监控的endpoint暴露
management.endpoints.web.exposure.include=*
3. 访问
访问http://localhost:9000/
七、部署
1. jar包(推荐)
-
切换到项目目录
-
使用
mvn package
打包 -
在target目录中找到jar包
-
使用
F:/Tools/JDK/bin/java.exe -jar SpringBoot-Deploy-0.0.1-SNAPSHOT.jar
运行 -
访问http://localhost:8080/hello/demo1
2. war包
二、进阶
前置一、parent
前置二、starter
前置三、引导类
- 带有@SpringBootApplication注解(该注解包含配置类注解)
- 程序的入口,扫描引导类所在包,获取容器对象再加载bean
- 带有@SpringBootTest注解
- 程序测试用的
前置四、内置服务器
- Tomcat(默认)
- jetty
- undertow
- netty
前置五、Restful风格
-
书写简化
-
隐藏资源访问行为,无法通过地址得知资源是何种操作
- 传统格式:http://localhost/user/getById?id=1
- Restful格式:http://localhost/user/1
-
标识符:
- GET 查询
- POST 新增/保存
- PUT 修改/更新
- DELETE 删除
-
注解:“*”表示Restful风格常用注解
-
@Controller类中的方法可以直接通过返回String跳转到jsp、ftl、html等模版页面。在方法上加@ResponseBody注解,也可以返回实体对象。@RestController类中的所有方法只能返回String、Object、Json等实体对象,不能跳转到模版页面。
- @RestController
- @Controller
- @ResponseBody*
- @RequsetParam:标识该形参接收正常风格的参数,/users?id=1(建议url参数和使用表单时使用)
- @RequsetBody*: 标识该形参接收json格式的参数,xhr.send({“name”:“张飞”})(建议多个参数时使用)
- @PathVariable*: 标识该形参接收Restful风格的参数,/users/1(建议1个参数时使用)
- @GetMapping*
- @PostMapping*
- @PutMapping*
- @DeleteMapping*
前置六、解决注解报错提示
spring-boot-configuration-processor
一、基础篇
一、配置(基础)
- 常用属性
- server.port:服务器端口
- spring.main.banner-mode:开启服务时的logo是否输出和输出位置
- spring.banner.image.location:开启服务时的logo
- logging.level.root:日志输出级别
- server.servlet.context-path:访问路径前缀,如http:localhost:8080/前缀/xxxx
二、配置文件分类
- application.properties格式为key-value
- application.yaml和application.yml格式为渐进式
- 配置文件需要对应各自的Dependencies
- __属性冲突优先级__properties>yaml>yml(推荐使用),属性会互补
三、yaml文件
- 大小写敏感
1. 数据格式
- 注释
#
- 字符串
name: 张飞
- 数字
number: 80
- boolean
flag: false
- 日期
birthday: 1973-01-23
- 对象
person:
name: 张飞
age: 18
- 普通数组
arr:
- 张飞
- 赵云
- 马超
arr: [张飞, 赵云, 马超]
- 对象数组
arr:
-
name: 张飞
age: 18
-
name: 马超
age: 20
arr: [{name: 张飞, age: 18}, {name: 马超, age: 20}]
- 属性引用
用于解决更改系统后需要更改所有目前前缀
var1: 我是
var2: ${var}傻逼 // 我是傻逼
- 转义字符
需要用双引号包裹内容
str: "我是傻逼吧\n哈哈哈哈" // 我是傻逼吧*换行*-哈哈哈哈
四、yaml数据读取
-
1.springBoot支持注解@Value,缺点:有多少属性类就需要多少个属性
- 单级获取@Value(“${name}”)
- 多级获取@Value(“${user.name}”)
- 普通数组获取@Value(“${arr[0]}”)
- 对象数组获取@Value(“${arr[0].name}”)
-
2.springBoot提供对象Environment+@Autowired自动装配
- 单级获取getProperty(“name”)
- 多级获取getProperty(“user.name”)
- 普通数组获取getProperty(“arr[0]”)
- 对象数组获取getProperty(“arr[0].name”)
-
3.springBoot提供注解@ConfigurationProperties和支持注解@Component
-
该对象名称必须要__小写__!!!
-
将yaml数据对象封装到java类中,该类有getter和setter方法、重写toString方法
-
该类有@Component(SpringIOCDI的注解)和@ConfigurationProperties(“yaml对象名称”)
-
@Component @ConfigurationProperties(prefix = "datasource") public class DataSource { 属性定义、getter和setter、toString } @Autowired public DataSource dataSource; @GetMapping("/test") public String test(){ return dataSource.toString(); }
-
五、整合(基础)
一、jUnit
-
springBoot项目默认自带jUnit,无需其他操作
-
在test中找到对应的引导测试类即可
-
支持注入对象
-
public interface Book { void save(); } @Repository public class BookImpl implements Book { @Override public void save() { System.out.println("save..."); } } @SpringBootTest class JavaSpringBoot2ApplicationTests { @Autowired Book book; @Test void contextLoads() { book.save(); } }
-
若该引导测试类在引导类同目录或者子目录下则可以正常使用
-
移动该引导测试类到不符合5的描述,则会导致无法正常测试
-
解决方案: @SpringBootTest(classes=JavaSpringBoot2ApplicationTests.class)或者加上@ContextConfiguration(JavaSpringBoot2Application.class)
二、MyBatis
-
选择MySQL Driver或者导入坐标:mybatis-spring-boot-starter和mysql-connector-java,版本会自动提供!!!
-
springBoot的三大配置文件均自带数据库相关属性
-
application.yaml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://101.43.117.227:3307/test?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456
-
开始测试()
-
@Mapper public interface BookDao { @Select("select * from l1 where age= ${age}") Book selectByAge(Integer age); } public class Book{ private String name; private Integer age; // getter和setter以及toString } @SpringBootTest class JavaSpringBoot2ApplicationTests { @Autowired BookDao book; @Test public void test1(){ System.out.println(book.selectByAge(18)); } }
-
@Mapper在此处的作用:
1.不用写Mapper映射文件(XML)
2.使用@Mapper将mapper类的接口交给Spring进行管理
3.为这个mapper接口生成一个实现类,让别的类进行引用
三、MyBatis-Plus
-
导入坐标mybatis-plus-boot-starter和mysql-connector-java
-
配置同上,接口类需继承MP提供的__BaseMapper类__
-
开始测试
-
@Mapper public interface UserDao extends BaseMapper<User> { } @TableName("tb_user") public class User { private Integer id; private String username; private String password; private String gender; private String addr; } @SpringBootTest class JavaSpringBoot2ApplicationTests { @Autowired UserDao user; @Test public void test2(){ System.out.println(user.selectById(1)); } }
四、Druid/C3P0
-
导入坐标druid-spring-boot-starter
-
在整合MyBatis的配置文件基础上加入spring.datasource.type或者另写一个
-
// 法一,通用型整合数据源,不是真正意义上的整合 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://101.43.117.227:3307/test?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource // 法二,druid数据源专用的,真正的整合 spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://101.43.117.227:3307/test?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource
二、开发篇
一、部署
-
spring-boot-devtools
二、配置(进阶)
一、绑定第三方bean
1. @ConfigurationProperties
-
开启属性绑定
-
加属性prefix:yml属性名
servers:
ipAddress: 123.456.789.66
port: 1234
timeout: -1
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://101.43.117.227:3307/test?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
// 启动类
@SpringBootApplication(scanBasePackages = "com.miao.Dao.Pojo")
// pojo类
@Component
@ConfigurationProperties(prefix = "servers")
public class User {
private String ipAddress;
private int port;
private long timeout;
xxx
}
// pojo类
@Bean
@ConfigurationProperties(prefix = "datasource")
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
2. @EnableConfigurationProperties
-
开启属性绑定,并设定bean,对应类不需要加__@Component__,会自动将其视为bean
-
加值:User.class或者{User.class, Servlet.class}
// 启动类
@SpringBootApplication(scanBasePackages = "com.miao.Dao.Pojo")
@EnableConfigurationProperties(User.class)
// pojo类
@ConfigurationProperties(prefix = "servers")
public class User {
private String ipAddress;
private int port;
private long timeout;
xxx
}
3. @Value
- 不支持松散绑定
二、常用计量单位
@DurationUnit(ChronoUnit.HOURS) // 时间范围
private Duration settimeout;
@DataSizeUnit(DataUnit.MEGABYTES) // 数据大小
private DataSize size;
三、数据校验
-
validation-api接口 hibernate-validator实现类
-
@Validated public class xxx{ @Max(value = 8888, message = "该属性值最大值不能超过8888") @NotEmpty private int port; }
四、进制转换
- yml格式会识别数字
password: 123456 视为十进制,解析成123456
password: 0127 视为八进制,解析成87(0开头0-7)
建议使用"0127"包裹即可
三、测试
四、数据层解决方案
一、SQL
二、NoSQL
五、整合(进阶)
六、监控
三、运维篇
一、工程打包
- Maven中取消test,再进行package
- java -jar xxx.jar即可运行