Springboot3自定义starter笔记

场景:抽取聊天机器人场景,它可以打招呼。 效果:任何项目导入此 starter

都具有打招呼功能,并且问候语中的人名需要可以在配置文件中修改。

  1. 创建自定义 starter 项目,引入 spring-boot-starter 基础依赖。
xml 复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 编写模块功能,引入模块所有需要的依赖。
  2. 编写 xxxAutoConfiguration 自动配置类,帮其他项目导入这个模块需要的所有组件。
  3. 编写配置文件 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定启动需要加载的自动配置。
  4. 其他项目引入即可使用

业务代码

java 复制代码
@Service
public class RobotService {

    @Autowired
    RobotProperties robotProperties;

    public String sayHello(){
        return "hello"+robotProperties.getName()+":"+robotProperties.getAge()+"邮箱"+robotProperties.getEmail();
    }
}

写下面代码为了进行属性绑定,配置文件(application.properties)配了什么属性项这个类里面都可以直接进行绑定关联(在配置文件中写的数据通过这个配置文件,在业务代码中引入RobotProperties robotProperties并进行自动注入,就会通过这个来获取配置文件中的属性)

java 复制代码
@ConfigurationProperties(prefix = "robot")
@Component
@Data
public class RobotProperties {
    private String name;
    private String age;
    private String email;
}
复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

基本抽取

  1. 创建starter项⽬,把公共代码需要的所有依赖导⼊ 把公共代码复制进来

    不选场景

    引入需要的web包

    复制代码
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

删除主程序类

在新项目中导入该starter

  1. ⾃⼰写⼀个 RobotAutoConfiguration ,给容器中导⼊这个场景需要的所有组件
    为什么这些组件默认不会扫描进去?
    starter所在的包和 引⼊它的项⽬的主程序所在的包不是⽗⼦层级

  2. 别⼈引⽤这个 starter ,直接导⼊这个 RobotAutoConfiguration ,就能把这个场景的组件导⼊进来

使用@EnableXxx机制

完全自动配置

  1. 依赖SpringBoot的SPI机制
  2. META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    ⽂件中编写好我们⾃动配置类的全类名即可
  3. 项⽬启动,⾃动加载我们的⾃动配置类
相关推荐
使一颗心免于哀伤5 小时前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
_落纸2 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE2 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha2 天前
SpringBoot
笔记·学习
Hello_Embed3 天前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中3 天前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
Grassto3 天前
RAG 从入门到放弃?丐版 demo 实战笔记(go+python)
笔记
Magnetic_h3 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
周周记笔记3 天前
学习笔记:第一个Python程序
笔记·学习
丑小鸭是白天鹅3 天前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin