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 {@AutowiredRobotProperties 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机制
完全自动配置
- 依赖SpringBoot的SPI机制
- META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
⽂件中编写好我们⾃动配置类的全类名即可 - 项⽬启动,⾃动加载我们的⾃动配置类