开发者

Springboot3自定义starter业务代码

目录
  • 业务代码
  • 基本抽取
    • 引入需要的web包
    • 完全自动配置

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

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

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</pythongroupId>
            <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指定启动需要加载的自动配置。其他项目引入即可使用

业务代码

Springboot3自定义starter业务代码

@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>
    &l编程客栈t;artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Springboot3自定义starter业务代码

基本抽取

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

Springboot3自定义starter业务代码

不选场景

Springboot3自定义starter业务代码

Springboot3自定义starter业务代码

引入需要的web包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</编程客栈groupId>
    <artifactId>lombok</artifactId>
    <optional>truhttp://www.devze.come</optional>
</dependency>

删除主程序类

Springboot3自定义starter业务代码

在新项目中导入该starter

Springboot3自定义starter业务代码

⾃⼰写⼀个 RobotAutoConfiguration ,给容器中导⼊这个场景需要的所有组件

为什么这些组件默认不会扫描进去?

starter所在的包和 引⼊它的项⽬的主程序所在的包不是⽗⼦层级

Springboot3自定义starter业务代码

Springboot3自定义starter业务代码

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

Springboot3自定义starter业务代码

完全自动配置

  • 依赖SpringBoot的SPI机制
  • META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

    ⽂件中编写好我们⾃动配置类的全类名即可

  • 项⽬启动,⾃动加载我们的⾃动配置类

Springboot3自定义starter业务代码

到此这篇关于Springboot3自定义starter业务代码的文章就介绍到这了,更android多相关Springboot3自定义starter内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜