自定义springboot-stater

对于有些场景,我们需要自定义start才能满足。
可参考org.mybatis.spring.boot:
image

自定义starter的流程如下:
image
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原理发现

posted @ 2022-07-29 14:48  swayer  阅读(186)  评论(0编辑  收藏  举报