java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot3自定义starter

Springboot3自定义starter业务代码

作者:z542968z

在Spring Boot中,starter是一种特殊的依赖,它可以帮助开发人员快速引入和配置某个特定的功能模块,这篇文章给大家介绍Springboot3自定义starter业务代码的相关知识,感兴趣的朋友跟随小编一起看看吧

场景:抽取聊天机器人场景,它可以打招呼。 效果:任何项目导入此 starter
都具有打招呼功能,并且问候语中的人名需要可以在配置文件中修改。

创建自定义 starter 项目,引入 spring-boot-starter 基础依赖。

    <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>

编写模块功能,引入模块所有需要的依赖。编写 xxxAutoConfiguration 自动配置类,帮其他项目导入这个模块需要的所有组件。编写配置文件 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定启动需要加载的自动配置。其他项目引入即可使用

业务代码

@Service
public class RobotService {
    @Autowired
    RobotProperties robotProperties;
    public String sayHello(){
        return "hello"+robotProperties.getName()+":"+robotProperties.getAge()+"邮箱"+robotProperties.getEmail();
    }
}

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

@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>

基本抽取

创建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

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

别⼈引⽤这个 starter ,直接导⼊这个 RobotAutoConfiguration ,就能把这个场景的组件导⼊进来 使用@EnableXxx机制

完全自动配置

到此这篇关于Springboot3自定义starter业务代码的文章就介绍到这了,更多相关Springboot3自定义starter内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文