SpringBoot3自定义Starter步骤

参考: https://www.yuque.com/leifengyang/springboot3/lliphvul8b19pqxp#fR0xi

想要实现一个聊天机器人Starter:

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

核心步骤总结:
● 1. 创建自定义starter项目,引入spring-boot-starter基础依赖
● 2. 编写模块功能,引入模块所有需要的依赖。
● 3. 编写xxxAutoConfiguration自动配置类,帮其他项目导入这个模块需要的所有组件
● 4. 编写配置文件META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定启动需要加载的自动配置
● 5. 其他项目引入即可使用

源码地址: https://gitee.com/leifengyang/spring-boot-3/tree/master/boot3-08-robot-starter
RobotController和RobotService只是业务逻辑,实现机器人sayHello的功能

细节1: 定义属性配置类,并且和配置文件进行绑定
RobotProperties: 定义属性类,用来配置stater,和配置文件进行绑定,这样一来,使用这个Starter的人,就可以用配置文件来定制使用我们的Starter

@ConfigurationProperties(prefix = "robot")  //此属性类和配置文件指定前缀绑定
@Component
@Data
public class RobotProperties {

    private String name;
    private String age;
    private String email;
}

细节2: 导入spring-boot-configuration-processor,这样别人在使用配置文件自定义的properties的时候会有提示(在application.properties里面敲robot的时候会提示)

<!--        导入配置处理器,配置文件自定义的properties配置都会有提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

1.实现机器人打招呼的业务逻辑

实现RobotController:

@RestController
public class RobotController {

    @Autowired
    RobotService robotService;

    @GetMapping("/robot/hello")
    public String sayHello(){
        String s = robotService.sayHello();
        return s;
    }
}
实现RobotService:  
```java
@Service
public class RobotService {

    @Autowired
    RobotProperties robotProperties;

    public String sayHello(){
        return "你好:名字:【"+robotProperties.getName()+"】;年龄:【"+robotProperties.getAge()+"】";
    }
}

2. 自己实现一个配置类

自动配置类里面用import导入所有组件,别的项目在使用的时候直接import这个自动配置类就行

//给容器中导入Robot功能要用的所有组件
@Import({RobotProperties.class, RobotService.class})
@Configuration
public class RobotAutoConfiguration {
    @Bean //把组件导入到容器中
    public RobotController robotController(){
        return new RobotController();
    }
}

3. 自动配置(用的多)

在自己的Stater里面创建META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件,在里面中编写好我们自动配置类的全类名即可。例如 com.atguigu.boot3.starter.robot.RobotAutoConfiguration

自定义的starter里面放这个文件,文件里面配置好要加载的自动配置类,别的项目啥都不用做,直接导starter就能使用

4. 还可以使用@EnableXxx机制(可选)

别的项目在使用我们的starter的时候,使用import导入自动配置类比较麻烦,而且可能不知道要导入哪个类,就可以自定义Enablexxx注解,别人用的时候直接在springboot的主程序main方法上标注这个注解就行

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import(RobotAutoConfiguration.class) // 导入配置类
public @interface EnableRobot {


}

别人引入starter需要使用 @EnableRobot开启功能

总结:
自定义starter,提供给别人使用的三种方式:
1.手动使用 @Import 注解,导入自动配置类
2.定义 @EnableXXX 注解,手动开启
3.SPI 机制,自动配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值