SpringBoot的starter配置方法

一,starter模块整体结构

starter的整体实现逻辑主要由两个基本部分组成:

xxxAutoConfiguration:自动配置类,对某个场景下需要使用到的一些组件进行自动注入,并利用xxxProperties类来进行组件相关配置

xxxProperties:某个场景下所有可配置属性的集成,在配置文件中配置可以进行属性值的覆盖 按照SpringBoot官方的定义,Starer的作用就是依赖聚合,因此直接在starter内部去进行代码实现是不符合规定的,starter应该只起到依赖导入的作用,而具体的代码实现应该去交给其他模块来实现,然后在starter中去引用该模块即可,因此整体的starter的构成应该如下图所示:

 

可见starter模块依赖了两部分,一部分是一些常用依赖,另一部分就是对自动配置模块的依赖,而xxxAutoConfigurationxxxProperties的具体实现,都封装在自动配置模块中,starter实际是通过该模块来对外提供相应的功能。

 

 

二,autoconfigure模块开发

  2.1依赖引入

<dependencies>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-autoconfigure</artifactId>
        <!-- 包含很多与自动配置相关的注解的定义,必须要引入 -->
     </dependency>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-configuration-processor</artifactId>
       <!-- 非必须的,引入后可以在配置文件中输入我们自定义配置的时候有相应的提示,也可以通过其他.properties文件为相关类进行属性映射(SpringBoot默认使用application.yml)-->
         <optional>true</optional>
     </dependency>
 <dependencies>

 

  2.2 autoconfigure模块中最重要的就是自动配置类的编写,它为我们实现组件的自动配置与自动注入。在编写自动配置类的时候,我们应该要考虑向容器中注入什么组件,如何去配置它。

@Configuration
@ConditionalOnxxx
@ConditionalOnxxx//限定自动配置类生效的一些条件
@EnableConfigurationProperties(xxxProperties.class)
public class xxxAutoConfiguration {
 @Autowired
 private xxxProperties properties;
    @Bean
    public static BeanYouNeed beanYouNeed() {
     BeanYouNeed bean = new BeanYouNeed()
     bean.setField(properties.get(field));
     bean.setField(properties.get(field));
     bean.setField(properties.get(field));
        ......
    }
}

 

2.3 xxxProperties的实现

这是跟配置文件相绑定的类,里边的属性就是我们可以在配置文件中配置的内容,然后通过@ConfigurationProperties将其与配置文件绑定:

@ConfigurationProperties(prefix = "your properties") //使用@ConfigurationProperties注解绑定配置文件
public class xxxProperties {

    private boolean enabled = true;

    private String clientId;

    private String beanName;

    private String scanBasePackage;

    private String path;

    private String token;
}

 

2.4 配置spring.factories文件

在resource目录下新建META-INF文件夹,在文件夹下新建spring.factories文件,并添加写好的xxxAutoConfiguration类:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meituan.xframe.boot.mcc.autoconfigure.xxxAutoConfiguration

 

三 Starter模块开发

starter模块中只进行依赖导入,在pom文件中添加对autoconfigure模块的依赖,并添加一些其他必要的依赖项:

 

<dependencies>
 ================================================================
 <!--添加了对autoconfigure模块的引用-->
     <dependency>
         <groupId>com.test.starter</groupId>
         <artifactId>xxx-spring-boot-autoconfigure</artifactId>
     </dependency>
 ===============================================================
 <!--其他的一些必要依赖项-->
     <dependency>
         <groupId>commons-collections</groupId>
         <artifactId>commons-collections</artifactId>
     </dependency>
 </dependencies>

 

这两个模块都开发完成之后,通过mvn install命令或者deploy命令将包发布到本地或者中央仓库,即可直接在其他项目中引用我们自定义的starter模块了

 

posted @ 2021-12-20 14:41  cloxi  阅读(702)  评论(0)    收藏  举报