Spring Boot基础应用笔记
Spring Boot基础应用笔记✊
Spring Boot是什么?和 Spring什么关系?🧐
🥺自我总结:Spring Boot框架是为了快速开发关于Spring项目的服务性框架,大大减少了原始开发Spring项目中会出现的版本依赖问题(起步依赖),以及诸多对象注入的繁琐问题(自动配置),使我们在开发Spring项目时更专注于业务内容的开发,并非在项目的搭建过程中消耗更多时间。
Spring Boot首听名词:约定大于配置
此篇文章忽略的内容🫣
- Spring Boot项目搭建(官网,idea脚手架,maven自搭建)
- Spring Boot项目结构(配置文件,启动类)
- 起步依赖,自动配置的原理
- 配置文件的种类(properties,yaml,yml)
- Spring Boot项目中的配置类(@SpringBootConfiguration or @Configuration)
- Spring Boot内嵌的RandomValuePropertySource类(${random.*})
- 配置文件中的参数的引用(${参数})
- Thymeleaf视图模板技术
正式开始文档的内容🥰
Spring Boot项目父工程的pom.xml文件内容🥸
使用Maven父子工程之间的依赖传递性,在父工程中定义了子工程公共的内容坐标,如下:
<?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>
<groupId>com.yang</groupId>
<artifactId>springboot-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
......
</modules>
<!--父工程定义项目的相关属性-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
</properties>
<!--父工程定义引入坐标的版本锁定-->
<dependencyManagement>
<dependencies>
<!--springboot版本锁定-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.13</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--父工程引入公共坐标-->
<dependencies>
<!--web相关功能坐标-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok工具-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!--maven项目编译插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Spring Boot单元测试
Spring Boot项目中单元测试功能也是需要引入单元测试功能启动坐标
<!--springboot项目单元测试工具包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--junit单元测试工具包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
编写一个简单的Controller
@RestController
public class DemoController {
@GetMapping("/demo")
public String demo(){
return "中华人名共和国万岁";
}
}
之后进行单元测试
1: 使用 jupiter 中的API进行测试
package com.yang;
import com.yang.controller.DemoController;
import org.junit.jupiter.api.Test; // 注意这里引入的包
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author ......
* @date 2023/2/21 下午4:33
*/
@SpringBootTest
public class DemoControllerTest {
@Autowired
private DemoController demoController;
@Test
public void test01(){
String demo = demoController.demo();
System.out.println(demo);
}
}
这里在测试类中使用 @SpringBootTest 注解标注类为测试类,使用 @Test 注解在方法上为测试方法进行单元测试
2:使用 junit 中的API进行测试
package com.yang;
import com.yang.controller.DemoController;
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;
/**
* @author ......
* @date 2023/2/21 下午4:43
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoControllerTest2 {
@Autowired
private DemoController demoController;
@Test
public void test01() {
System.out.println(demoController.demo());
}
}
这里使用的是junit工具的API,需要添加的是 @RunWith(SpringRunner.class)
以上两种单元测试中,都是需要在一定的包关系下创建测试类并运行的
不然以下代码会错误找不到
@Autowired
private DemoController demoController;
Spring Boot自定义配置文件内容🥳
🤣案例:某个实体类或配置类需要读取我们的配置文件中的属性来完成值的注入,那下面的这些例子就可以完成,注意要使用的注解。
😀使用原配置文件自定义属性注入实体类,并将实体类注入IOC容器中的使用:
@Data
@ConfigurationProperties(prefix = "student")
@Component
public class Student implements Serializable {
private static final long serialVersionUID = 4890265452830177090L;
/**
* 学号
*/
private Short id;
/**
* 姓名
*/
private String name;
/**
* 生日
*/
private Date birthday;
/**
* 爱好
*/
private List<String> hobby;
}
Student对象实体类
注解 | 描述 |
---|---|
@Data | lombok工具中注解,用于生成实体类中的常用必要方法 |
@Component | spring中注解,用于创建对象并注入到IOC容器中(默认单例模式) |
@ConfigurationProperties(prefix = "student") | 读取配置文件内容,前缀为 prefix 定义的值 |
# 自定义属性
student:
id: 1001
name: 孙悟空
birthday: Sat Feb 18 11:41:36 CST 2023
hobby:
- 吃
- 喝
- 玩乐
application.yml配置文件内容
添加配置提示功能
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
添加完成后,重新构建项目 Build Project
注意事项:自定义配置的属性必须和实体类中的成员属性一致
此时已经将自定义配置的内容加载到实体类中并注入到了IOC容器中并使用对象了
@RestController
public class StudentController {
@Autowired
private Student student;
@GetMapping("/getStudent")
public Student getStudent() {
return student;
}
}
web接口测试
代码,测试图
😀读取自定义配置文件中的自定义配置属性值到实体中,并注入到IOC容器中使用该对象
person.id=1002
person.name=唐三藏
person.numberPhone=16888888888
person.properties自定义配置文件内容
@Data
@Component
@PropertySource("classpath:person.properties")
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
private static final long serialVersionUID = 6322498600532324455L;
/**
* 编号
*/
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 手机号
*/
private String numberPhone;
}
Person实体类
注解 | 描述 |
---|---|
@PropertySource("classpath:person.properties") | 读取自定义配置文件 |
代码,测试图
😀配置类中加载配置文件内容
teacher:
name: coderyang
application.yml文件内容
@Data
public class Teacher implements Serializable {
private static final long serialVersionUID = 4107746465747905270L;
/**
* 教师姓名
*/
private String name;
}
Teacher实体类
@SpringBootConfiguration
@ConfigurationProperties(prefix = "teacher")
@Data
public class TeacherConfig {
private String name;
@Bean
public Teacher teacher(){
Teacher teacher = new Teacher();
teacher.setName(name);
return teacher;
}
}
Teacher配置类
代码,测试图
🥹总结:在使用 @ConfigurationProperties 注解来读取配置文件的内容时,必须要配合其余两个注解来使用达到有意义的目的:@SpringBootConfiguration or @Component
除了使用 @ConfigurationProperties 注解以外,还有就是Spring自己的 @value 注解来读取配置文件内容,但是 @value 注解有着局限性,只能读取简单的数据类型,对象类型 和 集合类型读取不了。🫵
Spring Boot项目开发时的热部署🔥
项目开发运行后,编写了新的代码,无需手动重启项目,项目在一定时间内进行自动重启动作,进行项目的自动编译更新,经过测试,项目中无论代码变化还是配置文件变化,都会触发自动编译更新重启动作🤩
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
添加热部署功能起步依赖
开发工具idea的相关配置
快捷键:command + option + shift + / 打开注册器
👀以上操作是在idea2019.3版本完成开发时热部署实现的相关设置
在新版的idea中(2022版本我用过),是在设置中 ->> 其他设置 中进行开启的
Spring Boot项目参数校验🧐
前后端分离项目,前端传入后端接口时接收的数据,需要进行参数校验工作(无论何时,都需要对即将使用的数据进行校验(避免空指针异常))
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
添加Spring Boot校验工具起步依赖
validation 工具常用的注解如下:
😀校验接口中一个或多个简单的数据类型时:
- 未添加校验功能时
@RestController
public class ValidationController {
@GetMapping("/vc01/{name}/{num}")
public String vc01(@PathVariable("name") String name, @PathVariable("num") Integer num) {
int length = name.length();
byte b = num.byteValue();
return "success";
}
}
启动项目,不传递参数值进行测试运行,效果如下:
😆很有意思,使用Restful风格的接口代码,既然不传递参数直接就是404,有点意思,感觉有时候get请求使用Restful风格避免后台代码出现错误诶🤭 更换代码如下:
@GetMapping("/vc02")
public String vc02(String name, Integer num) {
int length = name.length();
byte b = num.byteValue();
return "success";
}
再测试
后台500错误,空指针异常就来了
- 添加参数校验功能时🫡
@RestController
@Validated
public class ValidationController {
@GetMapping("/vc02")
public String vc02(@NotBlank(message = "name属性的值不能为空") String name, @NotNull(message = "num的值不能为空") Integer num) {
int length = name.length();
byte b = num.byteValue();
return "success";
}
}
👺类上需要添加:@Validated 注解来触发参数上的校验注解
以及在需要校验的参数上添加校验注解:@NotBlank(message = "name的值不能为空的"),message属性为当发生校验失败出现的异常信息内容
再测试:
依旧500错误,像是自定义异常注解的升级,自带了为程序判断参数的合法性,抛出了:ConstraintViolationException异常类
😀检验接口中参数为对象数据类型时:
案例:常见的后端接口接收前端发来的数据时,使用的是DTO对象进行接收封装,所以我们需要创建对应的DTO对象,并且在DTO对象中进行校验规则的定义
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
@Data
public class DemoDTO {
@NotNull(message = "id 不能为空")
private Integer id;
@NotBlank(message = "name 不能为空")
private String name;
@NotEmpty(message = "hobby 不能为空")
private List<String> hobby;
}
案例接收数据实体类
@GetMapping("/vc03")
public String vc03(@Validated DemoDTO demoDTO) {
return "success";
}
👺注意:此时,就需要在要校验对象的参数上添加 @Validated 校验注解来进行生效
产生BindException绑定异常
到这里参数校验的工作完成了一半,实现了注解捕获参数不合法并抛出异常,这样默认如果参数出现问题会抛出Validated工具中的异常信息,之后需要捕获这些异常进行合理、统一的处理方式
全局异常捕获处理器🪤
我将使用的是springwebmvc的异常捕获处理方式(注解方式),代码如下
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolationException;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 获取参数校验不通过产生的异常进行处理
*
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
public String constraintViolationException(ConstraintViolationException e) {
// 应该返回全局统一响应对象,这里省略此步
return "简单类型校验 出现约束冲突异常" + e.getMessage();
}
@ExceptionHandler(BindException.class)
public String methodArgumentNotValidException(BindException e) {
// 应该返回全局统一响应对象,这里省略此步
return "对象类型校验 出现约束冲突异常" + e.getMessage();
}
/**
* 捕获未知异常进行统一处理
*
* @return
*/
@ExceptionHandler(Exception.class)
public String runtimeException(Exception e) {
e.printStackTrace();
// 应该返回全局统一响应对象,这里省略此步
return "出现运行时未知异常";
}
}
注解 | 描述 |
---|---|
@RestControllerAdvice | 控制器增强注解 |
@ExceptionHandler(Exception.class) | 异常捕获,参数为程序已知的异常 |
此时,程序呢,异常会产生,也会被捕获,但是捕获到会进行统一的处理,日志记录,统一返回响应前端内容
Spring Boot项目系统运行指标和Spring Boot Admin🫠
查看Spring Boot项目运行时的各个指标
😀在被监控的项目中添加如下起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.6.11</version>
</dependency>
😀被监控的项目开启被监控项目各个访问接口,以及连接可视化服务SpringBootAdmin服务
management:
endpoints:
web:
exposure:
include: "*"
spring:
boot:
admin:
client:
# springboot admin服务的地址
url: http://IP地址:端口
😀SpringBootAdmin服务是一个WEB项目,也需要添加一些起步依赖,起步依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.6.11</version>
</dependency>
启动类添加相应注解 @EnableAdminServer
@SpringBootApplication
@EnableAdminServer
public class SpringbootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAdminApplication.class,args);
}
}
这就准备好了最基本的SpringBootAdmin服务啦🤫
先启动SpringBootAdmin服务程序,再启动被监控的客户端程序。
spring:
application:
name: 被监控的项目名称
最好加上项目的名称,便于在监控平台中分辨。
SpringBootAdmin监控各个SpringBoot项目系统运行状态
Spring Boot项目日志管理🫤
日志这项技术在项目中必不可少,但是在我的技术圈中,日志技术略显模糊,只知道使用日志记录一些需要记录的内容,最难的是日志配置文件的编写,没有进行系统的学习,日常也是抄抄,我记得在es那里,日志显的尤为重要,记录日志,es读取日志,分析日志内容等操作,这里我将笔记一份用的不错的日志配置文件。
Spring Boot默认使用的是Logback日志工具。那Logback工具的配置文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--定义日志文件的存储地址-->
<property name="LOG_HOME" value="${catalina.base}/logs/"/>
<!-- 控制台输出 -->
<appender name="Stdout" class="ch.qos.logback.core.ConsoleAppender">
<!-- 日志输出编码 -->
<layout class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/server.%d{yy99-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 日志输出级别 -->
<root level="info">
<appender-ref ref="Stdout"/>
<appender-ref ref="RollingFile"/>
</root>
</configuration>
logback.xml文件
如何使用呢?代码如下:
// 核心导入的包
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class DemoVoController {
// 创建日志对象
private final static Logger LOGGER = LoggerFactory.getLogger(DemoVoController.class);
@PostMapping("/dvc")
public String demoVoC(@Validated @RequestBody DemoVo demoVo, HttpServletRequest request) {
// 打印日志 控制台以及文件记录
LOGGER.info(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()) + "访问了" + request.getRequestURI() + "路径");
return "success";
}
}
以上为日志文件内容(一部分)
Spring Boot项目打包运行🤤
我先记录一下我项目的结构
父子聚合工程(父工程负责依赖的版本管理,子工程实现功能需求),在打包子工程时添加如下工具即可(父子工程中都添加了)
<build>
<plugins>
<!-- springboot项目打包插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
然后打包,运行
测试接口OK👌
Spring Boot项目多环境配置😈
一个项目需要在多种环境下开发运行测试上线,那总不能一直改动配置文件吧,那就在启动项目时确定环境的配置内容。
配置文件名的编写格式:application-环境名.properties|yml
打包,运行时的命令区分运行哪个配置文件:
java -jar jar包名 --spring.profiles.active=环境名[dev|test]
Docker部署Spring Boot项目🫣
暂时不是那么会,后续补上
更新:简单的去看了一眼,使用DockerFile来 引入打好的包,配置好,build成Docker镜像运行即可,这里我放在Docker笔记里吧
Spring Boot定时任务🫡
我学习定时任务的时候就直接学习了Spring Boot的定时任务,但是也听说了这些工具,但是好像不常用,也不好用:
- Java自带的java.util.Timer类
- Quartz
Spring3.0以后自带Spring Task,可以将它看成一个轻量级的Quartz,使用起来比Quartz简单许多🤠
我这里不将启动定时任务的注解写到程序的启动类中,而是写到定时任务的配置文件中,就是为了让程序启动类的干净整洁(那程序的启动类还是那个简简单单的启动类(模板代码))
@SpringBootConfiguration
@EnableScheduling
public class TaskConfig {
}
task配置类配置类启动定时任务功能
注解 | 描述 |
---|---|
@EnableScheduling | 开启定时任务功能 |
👀编写一个简单的定时任务,每5秒执行一次
@Component
public class TaskDemo {
@Scheduled(cron = "0/5 * * * * ?")
public void task01() {
System.out.println("每5秒执行一次的代码"+ DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
}
}
每5秒执行一次的代码11:38:50
每5秒执行一次的代码11:38:55
每5秒执行一次的代码11:39:00
每5秒执行一次的代码11:39:05
每5秒执行一次的代码11:39:10
执行效果图
注解 | 描述 |
---|---|
@Scheduled() | 定时任务,写在方法上 |
属性 | 描述 |
---|---|
cron = "0/5 * * * * ?" | cron表达式 |
fixedDelay = 5000 | 单位毫秒,任务立即执行,当整个任务运行结束后,再计算下次运行的时间 |
fixedRate = 5000 | 单位毫秒,任务立即执行,不等当整个任务运行结束后,直接计算下次运行的时间 |
initialDelay = 3000 | 单位毫秒,任务不立即执行,等项目启动指定时间后,执行任务 |
😊cron的表达式编写帮助网站在线Cron表达式生成器🤭
其余代码:
/**
* 立即执行 当整个任务结束后 再进行计算下次运行的时间
*/
@Scheduled(fixedDelay = 5000)
public void task02() throws InterruptedException {
Thread.sleep(2000);
System.out.println("task02任务:" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
}
/**
* 立即执行 不等整个任务结束后 直接进行计算下次运行的时间
*/
@Scheduled(fixedRate = 5000)
public void task03() throws InterruptedException {
Thread.sleep(2000);
System.out.println("task03任务:" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
}
/**
* 不立即执行 等项目启动后3秒后 执行任务
*/
@Scheduled(fixedRate = 5000,initialDelay = 3000)
public void task04() throws InterruptedException {
System.out.println("task04任务:" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
}
🤯Spring Task定时器默认是单线程的,如果项目中使用多个定时器, 使用一个线程会造成效率低下。代码如下:
@Scheduled(cron = "0/2 * * * * ?")
public void task05(){
System.out.println("task05任务:" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
}
@Scheduled(cron = "0/2 * * * * ?")
public void task06() throws InterruptedException {
Thread.sleep(5000);
System.out.println("task06任务:" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
}
task06任务会占用线程,导致task05任务无法执行,那就需要创建定时任务线程池来完成每个定时任务的互不干扰😫
@SpringBootConfiguration
public class TaskConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 创建任务线程池
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
}
}
以上配置即可完成创建多个定时任务的线程分配✊
自定义starter启动坐标🤠
开发过程中,经常会有一些独立于业务之外的配置模块。如果我们将这些可独立于业务代码之外的功能配置模块封装成一个个starter,复用的时候只需要将其在pom中引用依赖即可,SpringBoot为我们完成自动装配,SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter命名规则。以区分SpringBoot生态提供的starter。
1:第一步:创建Maven项目工程,引入相应的一些工具坐标
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--自动配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.6.13</version>
</dependency>
<!--配置提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.6.13</version>
<optional>true</optional>
</dependency>
<!--lombok工具-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>
2:第二步:编写使用到的实体类
package com.yang.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* @author ......
* @date 2023/2/21 下午5:30
* 简单的一个对象
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EnableConfigurationProperties(SimpleBean.class)
@ConfigurationProperties(prefix = "simplebean")
public class SimpleBean {
private Integer id;
private String name;
}
关键注解 | 描述 |
---|---|
@EnableConfigurationProperties(SimpleBean.class) | 需要自动加载的类 (本类字节码对象) |
3:第三步:编写配置文件
package com.yang.config;
import com.yang.model.SimpleBean;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
/**
* @author ......
* @date 2023/2/21 下午5:33
*/
@SpringBootConfiguration
@ConditionalOnClass
public class MyAutoConfig {
static {
System.out.println("MyAutoConfig init......");
}
@Bean
public SimpleBean simpleBean() {
return new SimpleBean();
}
}
关键注解 | 描述 |
---|---|
@ConditionalOnClass | 当类路径classpath下有指定的类的情况下进行自动配置 |
4:第四步:在resources下创建 /META-INF/spring.factories文件,编写自动配置的类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yang.config.MyAutoConfig
5:第五步:打包自定义starter,其余项目引入自定义的starter进行使用
<dependency>
<groupId>com.yang</groupId>
<artifactId>yang-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
配置文件可配置自定义starter中的对象属性
simplebean:
id: 1001
name: yang
引入自动配置的对象进行使用
@RestController
public class ZDYController {
@Autowired
private SimpleBean simpleBean;
@GetMapping("/simpleBean")
public SimpleBean simpleBean(){
return simpleBean;
}
}
引入自定义starter启动项目的截图
接口测试图
转载自:https://juejin.cn/post/7201400444873261117