springboot自定义starter

205 阅读1分钟

springboot自定义starter,我们可以吧项目中的一些bean给抽离出来,封装成starter个各个项目使用,以前我在某个中厂的业务中台的时候,经常封装一些starter组件给各个业务线使用

Spring 官方 Starter通常命名为`spring-boot-starter-{name}` 如 `spring-boot-starter-web`,
Spring官方建议非官方Starter命名应遵循`{name}-spring-boot-starter`的格式。

demo1

步骤

  1. 添加spring.factories
  2. 编写自动配置类
  3. 编写属性类
  4. 测试:springboot-restful
  5. 具体的demo参考:springboot-starter
1. 添加spring.factories
`resources/META-INF/`下创建`spring.factories`文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xncoding.starter.config.ExampleAutoConfigure

2. 编写自动配置类

@Configuration
@ConditionalOnClass(ExampleService.class)
@EnableConfigurationProperties(ExampleServiceProperties.class)
public class ExampleAutoConfigure {

    private final ExampleServiceProperties properties;

    @Autowired
    public ExampleAutoConfigure(ExampleServiceProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "example.service", value = "enabled",havingValue = "true")
    ExampleService exampleService (){
        return  new ExampleService(properties.getPrefix(),properties.getSuffix());
    }

}


1.当classpath下发现该类的情况下进行自动配置,@ConditionalOnClass(ExampleService.class)
2.Spring Context中不存在该Bean时。@ConditionalOnMissingBean
3.当配置文件中example.service.enabled=true时。@ConditionalOnProperty(prefix = "example.service", value = "enabled",havingValue = "true")


3. 编写属性类


@ConfigurationProperties("example.service")
public class ExampleServiceProperties {
    private String prefix;
    private String suffix;

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}


配置属性类ExampleServiceProperties,加注解
@ConfigurationProperties("example.service")

自动配置类ExampleAutoConfigure,加注解
@EnableConfigurationProperties(ExampleServiceProperties.class)

这样就可以在自动配置类中引入需要的参数了

我们需要使用的bean:ExampleService是在自动配置类当中来实例化的

4. 测试

/**
 * @Author: dingyawu
 * @Description: 自定义测试自己封装的starter
 * @Date: Created in 22:36 2022/11/9
 */
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {

    @Autowired
    private ExampleService exampleService;


    @Test
    public void testStarter() {
        System.out.println(exampleService.wrap("hello"));
    }
}

<dependency>
    <groupId>com.xncoding</groupId>
    <artifactId>springboot-starter</artifactId>
    <version>1.0.0-SNAPSHOT</version>
</dependency>

demo2

一个完整的Spring Boot Starter可能包含以下组件:

-   **autoconfigure**模块:包含自动配置的代码
-   **starter**模块:提供对**autoconfigure**模块的依赖,以及一些其它的依赖

我参考的这篇blog:https://www.cnblogs.com/cjsblog/p/10926408.html