3分钟实现一个自定义的springboot-starter

  springboot-starter是springboot的启动依赖,实现原理就是利用了springboot的自动化配置功能.

自定义starter主要包括以下几点:创建自动配置类、需要自动注入spring容器的组件类 、组件属性类、对spring.factories进行配置

第一步,先创建一个简单的maven项目,项目pom.xml文件内容如下

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cwp</groupId>
  <artifactId>cwp-spring-boot-starter</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>cwp-spring-boot-starter</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-autoconfigure</artifactId>
          <version>2.2.1.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.12</version>
      </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

第二步:确定好装载属性的类CwpProperties,代码如下图:

 

package com.cwp;


import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 属性配置类
 */
//配置注解,获取cwp前缀开头的属性,注入类中
@ConfigurationProperties(prefix = "cwp")
public class CwpProperties {


    private  String  url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

 

第三步:确定好需要自动配置的组件类CwpService

package com.cwp;

/**
 * 业务组件service
 */
public class CwpService {

    private String  url;

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }
}

 

第四步:编写自动配置类 CwpServiceAutoConfiguration

package com.cwp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *  自动配置类
 */
@Configuration
@ConditionalOnClass(CwpService.class)  //当CwpService.class 在类路径中时生效
//当配置文件中存在cwp.enabled=open的配置值时生效,如果没配置这个属性值时也生效
@ConditionalOnProperty(prefix = "cwp",name = "enabled",havingValue = "open",matchIfMissing = true)
@EnableConfigurationProperties(CwpProperties.class)//开启配置属性注解,导入CwpProperties类,生成对应的bean
public class CwpServiceAutoConfiguration {

    @Autowired
    private  CwpProperties  cwpProperties;


   @Bean
   @ConditionalOnMissingBean  //当容器中不存在类型为CwpService的Bean时,生成对应的bean
   public CwpService getCwpService(){
       CwpService  cwpService=new CwpService();
       cwpService.setUrl(cwpProperties.getUrl());
       return cwpService;
   }
}

 

第五步:

在src/main/resources目录下新建一个META-INF目录 ,然后在META-INF下新建一个spring.factories文件,配置好自动配置类,内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.cwp.CwpServiceAutoConfiguration

 

本示例项目结构图如下:

 最好执行maven clean  install 安装到本地仓库或者上传到私服,其他项目引入这个stater依赖,就可以直接使用。

 

-----------------------我是华丽的分隔线------------------------

以下教程主要是简单介绍,web项目怎么使用使用自定义的starter

第一步:

项目pom.xml中声明自定义的starter依赖

具体pom.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.study</groupId>
    <artifactId>study-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>study-springboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.cwp</groupId>
            <artifactId>cwp-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

第二步:

  配置文件application.properties中,开启自动化配置,配置好自定义的属性值,需要和条件注解中设置的值保持一致,才会自动生成bean。本示例自动化配置生效属性值是cwp.enabled.如下所示:

cwp.enabled=open
cwp.url=www.baidu.com

第三步:(此处是自动化配置的目标) 组件中直接通过@Autowired,无需像spring容器中注册这个bean,已经通过自动化配置,组件已经自动注册并注入spring容器中了,直接使用@Autowire注解使用,如下图所示:

 

自动化配置常用的几个注解如下:

@ConfigurationProperties  :自动注入配置文件属性值

@Configuration: 配置类注解(此注解可以不用)

@ConditionalOnClass:类条件注解:当类路径中存在某个类文件时,配置生效

@ConditionalOnProperty:属性条件注解,当配置文件中存在某个属性值时条件生效,这个注解重点讲一下。
如以下示例所示:
//当配置文件中存在cwp.enabled=open的配置值时生效,由于属性配置了,matchIfMissing=true如果没配置这个属性值时也生效
@ConditionalOnProperty(prefix = "cwp",name = "enabled",havingValue = "open",matchIfMissing = true)

@Bean:生成bean并注入spring容器中

@ConditionalOnMissingBean:当spring容器中不存在类型为CwpService的Bean时,生成对应的bean

 

文章项目源码下载地址:

自定义springboot-starter组件项目源码下载地址:https://download.csdn.net/download/pingweicheng/12677198

使用了自定义springboot-starter组件的示例项目下载地址:https://download.csdn.net/download/pingweicheng/12677200

 

自定义Spring Boot Starter是一种用于简化Spring Boot应用程序配置和依赖管理的机制。它由几个组件组成,包括starter包、autoconfiguration包和配置文件。 首先,你需要创建一个Maven工程,并创建三个模块。其中,starter包负责引入依赖,autoconfiguration包负责实现装配。在autoconfiguration包中,你需要定义对应的properties类、configuration类和核心业务类。此外,你还需要在autoconfiguration包的/resources/META-INF/目录下添加spring.factories文件,并配置org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.qiejk.demo.springboot.autoconfiguration.DemoAutoConfiguration。这一步是Spring Boot装配的核心,只有添加了这个内容,Spring Boot才会进行自动装配。\[1\] 在父模块的pom文件中,你需要引入Spring Boot的依赖,例如spring-boot-starter-web,以及指定Spring Boot的版本。这样,你的自定义starter模块就可以基于Spring Boot进行开发和使用。\[2\] 最后,你需要创建一个配置文件,用于告诉Spring Boot在启动时扫描该配置文件,并将其中的配置类加载到Spring容器中。这个配置文件的作用是指定自动配置类的位置。\[3\] 通过以上步骤,你就可以创建自定义Spring Boot Starter,并在应用程序中使用它来简化配置和依赖管理。 #### 引用[.reference_title] - *1* [如何自定义springboot-starter](https://blog.csdn.net/sinat_29434159/article/details/123995794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot自定义Starter篇](https://blog.csdn.net/m0_46571920/article/details/122910726)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

成伟平2022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值