Skip to content
Go back

快速创建一个spring-boot-starter

Published:  at  11:26 AM

可以使用 spring spiimport 两种方法

1. 导入 starter 依赖

1.1. maven 管理工具

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

1.2. gradle 管理工具

  implementation 'org.springframework.boot:spring-boot-starter'

2. 使用spring spi

2.2. 创建实体类承载数据

@Data
@Builder
public class MyAuthor {
    private String name;
    private String blogSite;
}

2.2. 创建Properties暴露可选项

@Data
@ConfigurationProperties(prefix = "my.author")
public class MyProperties {

    private String name;
    private String blogSite;
}

2.3. 创建容器组件

@EnableConfigurationProperties(MyProperties.class)
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "author")
    public MyAuthor author(MyProperties myProperties) {
        return MyAuthor.builder()
                .name(myProperties.getName())
                .blogSite(myProperties.getBlogSite())
                .build();
    }

}

2.4. 使用spring spi导出配置类

spring spi 的路径

  1. META-INF/spring.factories 文件的 org.springframework.boot.autoconfigure.EnableAutoConfiguration 键下
  2. META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration. imports 文件内 (较新版本的springboot)

由于使用较新版本的springboot,我在 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件写入:

com.example.MyAutoConfiguration

2.5. 使用自动配置的组件

    @Bean
    CommandLineRunner commandLineRunner(MyAuthor author) {
        return args -> {
            System.out.println(author);
        };
    }

3. 使用Import提供可选特性支持

3.1. 创建一个可选的功能特性

可以是 @Configuration, ImportSelector, ImportBeanDefinitionRegistrar, 或者 regular component classes

这里选择 ImportSelector 方式实现相关功能 (这里实现的功能:打印 “com.newbieking” 包下的导入的类)

public class MyConfigurationSelector implements ImportSelector {
    private final static String PACKAGE_NAME = "com.example";

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        if (importingClassMetadata.getClassName().startsWith(PACKAGE_NAME)) {
            System.out.printf("[%s]bean name: %s\n", PACKAGE_NAME, importingClassMetadata.getClassName());
        }
        return new String[0]; // 可以通过返回配置类全限定类名,来实现添加功能特性
    }
}

3.2. 创建一个注解使用 @Import 注解导入功能组件

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(MyConfigurationSelector.class)
public @interface EnableMyFeature {
}

3.3. 在使用该功能的配置类上使用该注解

例如:

@EnableMyFeature
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Suggest Changes

Previous Post
Java中的字段拷贝复制