spring-boot-starter

121 阅读2分钟

项目结构图

1. 新建项目:jxorm-spring-boot

该项目是bom项目,统一管理jxorm starter和autoconfigure的依赖

2.新建module:jxorm-spring-boot-starter

该项目用于管理jxorm starter的依赖关系

3.新建module:jxorm-spring-boot-autoconfigure

该项目用于管理整个starter的功能,配置之类的内容

一个完整的starter包含两部分:starter和autoconfigure,starter中没有任何逻辑,只是依赖关系,autoconfigure中是具体的依赖关系,启动加载配置,项目配置和bean管理等。

1. 首先规划我们项目的配置,比如有以下配置:

cnc.orm.enable=false

2. 在module:autoconfigure下新建class如下:

@Data
@ConfigurationProperties(prefix = OrmProperties.ORM_PROPERTIES_PREFIX)
public class OrmProperties {
    static final String ORM_PROPERTIES_PREFIX="cnc.orm";

    public boolean enable=false;
}

该类对应着最后引用该starter的项目中application.properties中的配置。

其中@ConfigurationProperties的作用是把当前配置类映射到application.properties的哪个配置节点上。

有了以上配置类,如何生效呢?怎么才能和application.properties中配置做好映射呢?新建如下类:

@Configuration
@EnableConfigurationProperties(OrmProperties.class)
public class JxOrmAutoConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = "cnc.orm", name = "enable", havingValue = "true")
    public OrmTest ormTest() {
        OrmTest ormTest = new OrmTest();
        ormTest.setId(UUID.randomUUID().toString());
        ormTest.setName("ABCA");
        return ormTest;
    }
}

其中

@Configuration声明该类是一个配置类;

@EnableConfigurationProperties的作用是激活OrmProperties这个类

@ConditionalOnProperty的作用是如果项目的application.properties中存在cnc.orm.enable=true,则声明 OrmTest 这个 bean。

然后让JxOrmAutoConfiguration 被boot扫描到才行,在resources\META-INF\spring.factories下添加:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
jxorm.spring.boot.autoconfigure.JxOrmAutoConfiguration

当该jar被其他项目引用时,boot会到该文件中扫描这个JxOrmAutoConfiguration类,即生效。

3. 开始开发starter模块

添加 依赖:

(肯定要依赖autoconfigure,这样再其他项目引用starter时才会同时加载autoconfigure)

<dependency>
    <groupId>org.example</groupId>
    <artifactId>jxorm-spring-boot-autoconfigure</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

到此完事。

但是有的要求添加:

resources/META-INF/spring.providers文件,内添加:

providers: jxorm-spring-boot-autoconfigure

表用starter依赖这个包,但是不加也不影响使用,原因未知。

4. 其他项目直接引用starter即可。