SprinigBoot自定义Starter

自定义Starter


是什么

starter可以理解是一组封装好的依赖包,包含需要的组件和组件所需的依赖包,使得使用者不需要再关注组件的依赖问题

所以一个staerter包含

  1. 提供一个autoconfigure类
  2. 提供autoconfigure类的依赖
怎么做

创建starter大概需要

  1. 需要一个配置类bean,来填充配置
  2. 获取配置信息,注册到容器
  3. 将配置类加到自动配置

导入自动装配和Spring boot依赖

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

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

创建一个bean

@Data
public class HelloworldService {

    private String words;

    public String sayHello() {
        return "hello, " + words;
    }
}

创建peoperties类来自定义需要的参数,用来接收properties或者yml里的配置

//helloword就是配置的前缀
@ConfigurationProperties(prefix = "helloword")
public class HelloworldProperties {

    public static final String DEFAULT_WORDS = "world";

	//这个值就是helloword.words
    private String words = DEFAULT_WORDS;

    public String getWords() {
        return words;
    }

    public void setWords(String words) {
        this.words = words;
    }

}

创建configureation类来注册bean

将配置的参数注入到bean里,在注册到容器

@Configuration
//指定条件成立的情况下自动配置类生效(往哪装配)
@ConditionalOnClass(HelloworldService.class)
//让xxxProperties生效加入到容器中
@EnableConfigurationProperties(HelloworldProperties.class)
public class HelloworldAutoConfiguration {

    // 注入属性类
    @Autowired
    private HelloworldProperties hellowordProperties;

    @Bean
    // 当容器没有这个 Bean 的时候才创建这个 Bean
    @ConditionalOnMissingBean(HelloworldService.class)
    public HelloworldService helloworldService() {
        HelloworldService helloworldService = new HelloworldService();
        helloworldService.setWords(hellowordProperties.getWords());
        return helloworldService;
    }

}

在启动类里标明需要自动装配

@EnableAutoConfiguration//开启自动装配
@ComponentScan({"test"})
public class TestApplication {
}

最后是指定装配哪个配置类

在resources目录下创建META-INF文件夹

然后创建spring.factories标注需要装配的配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
test.config.HelloworldAutoConfiguration

最后就可以用这个starter了

首先导入这个starter

 <dependency>
            <groupId>org.example</groupId>
            <artifactId>test-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

然后导入HelloworldService这个bean

和在yml里配置参数

helloword:
  words  : hello

就完成了

posted @ 2021-12-26 15:52  阿弱  阅读(35)  评论(0编辑  收藏  举报