自定义springboot-stater
对于有些场景,我们需要自定义start才能满足。
可参考org.mybatis.spring.boot:
自定义starter的流程如下:
1.starter里引入autoconfigure
2.autoconfigure里引入spring-boot-starter
3.在autoconfigure里的META-INF/spring.factories文件中定义项目启动加载时指定的自动配置类
定义starter
创建maven项目hello-springboot-starter,在配置文件中添加autoconfigure坐标
<dependency>
<groupId>com.example</groupId>
<artifactId>hello-springboot-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
定义autoconfigure
创建hello-springboot-autoconfigure,在配置文件中引入spring-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
编写HelloAutoConfiguration
点击查看代码
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {
@ConditionalOnMissingBean(HelloService.class)
@Bean
public HelloService helloService(){
return new HelloService();
}
}
@Configuration:告诉容器这个是一个配置类
@EnableConfigurationProperties:像容器中导入配置类
@Bean:往容器中注册一个bean
@ConditionalOnMissingBean:条件判断,当容器中没有指定的bean时生效
编写xxxProperties绑定配置文件(如果有的情况下)
点击查看代码
@ConfigurationProperties("hello.user")
public class HelloProperties {
private String name;
private String address;
在META-INF下创建spring.factories文件,指定自动配置类:
点击查看代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.demo.config.HelloAutoConfiguration
其步骤就是引入
---XXXStarter
--------XXXAutoConfigure
--------------XXXProperties
具体原理可 参考Springboot原理发现
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix