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. 项⽬启动,⾃动加载我们的⾃动配置类
相关推荐
西岸行者4 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky4 天前
Django入门笔记
笔记·django
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意4 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发5 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
qianshanxue115 天前
计算机操作的一些笔记标题
笔记
土拨鼠烧电路5 天前
笔记11:数据中台:不是数据仓库,是业务能力复用的引擎
数据仓库·笔记
土拨鼠烧电路5 天前
笔记14:集成与架构:连接孤岛,构建敏捷响应能力
笔记·架构
烟花落o5 天前
栈和队列的知识点及代码
开发语言·数据结构·笔记·栈和队列·编程学习