Spring Boot - 手把手教小师妹自定义Spring Boot Starter

简介: Spring Boot - 手把手教小师妹自定义Spring Boot Starter


Pre

SpringBoot 最强大的功能就是把我们常用的场景抽取成了一个个starter(场景启动器),我们通过引入springboot 为我提供的这些场景启动器,再进行少量的配置就能使用相应的功能。

但有些时候,springboot也不能囊括我们所有的使用场景,往往我们需要自定义starter,来简化我们对springboot的使用。

那怎么搞呢?


自定义starter的套路

参照@WebMvcAutoConfiguration , 看看们需要准备哪些东西

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
    ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
.......
}

抽取以下

@Configuration  //指定这个类是一个配置类
@ConditionalOnXXX  //指定条件成立的情况下自动配置类生效
@AutoConfigureOrder  //指定自动配置类的顺序
@Bean  //向容器中添加组件
@ConfigurationProperties  //结合相关xxxProperties来绑定相关的配置
@EnableConfigurationProperties  //让xxxProperties生效加入到容器中

自动配置类要能加载需要将自动配置类,配置在META-INF/spring.factories中

我们参考下 spring-boot-starter

点击maven进去

有个 spring-boot-autoconfigure的依赖


步骤

所以总结下

  • 启动器(starter)是一个空的jar文件,仅仅提供辅助性依赖管理,这些依赖可能用于自动装配或其他类库。
  • 需要专门写一个类似spring-boot-autoconfigure的配置模块
  • 用的时候只需要引入启动器starter,就可以使用自动配置了

命名规范

官方命名空间

前缀:spring-boot-starter-

模式:spring-boot-starter-模块名

举例:spring-boot-starter-web、spring-boot-starter-jdbc

自定义命名空间

后缀:-spring-boot-starter

模式:模块-spring-boot-starter

举例:mybatis-spring-boot-starter


实战

创建一个父maven项目:springboot_custome_starter

新建一个maven工程, 父工程,pom类型 , src 目录 和 IDEA自动创建的.md文件,删除掉

pom 如下

<?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.3.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <packaging>pom</packaging>
    <groupId>com.artisan.customstarter</groupId>
    <artifactId>starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>starter</name>
    <description>SpringBoot自定义starter</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!--提供source-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

创建 两个Module: artisan-spring-boot-starter 和 artisan-spring-boot-starter-autoconfigurer

同样的方式创建


artisan-spring-boot-starter (空的jar文件,仅仅提供辅助性依赖管理)

pom

<?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">
    <parent>
        <artifactId>starter</artifactId>
        <groupId>com.artisan.customstarter</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <description>
        启动器(starter)是一个空的jar文件,
        仅仅提供辅助性依赖管理,
        这些依赖需要自动装配或其他类库。
    </description>
    <artifactId>artisan-spring-boot-starter</artifactId>
    <dependencies>
        <!--引入autoconfigure-->
        <dependency>
            <groupId>com.artisan.customstarter</groupId>
            <artifactId>artisan-spring-boot-starter-autoconfigurer</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <!--如果当前starter 还需要其他的类库就在这里引用-->
    </dependencies>
</project>

如果使用spring Initializr创建的需要删除 启动类、resources下的文件,test文件。


artisan-spring-boot-starter-autoconfigurer

pom

<?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">
    <parent>
        <artifactId>starter</artifactId>
        <groupId>com.artisan.customstarter</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>artisan-spring-boot-starter-autoconfigurer</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--‐导入配置文件处理器,配置文件进行绑定就会有提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

关于自动提示的jar ,引入spring-boot-configuration-processor之后, 编译之后就会在META-INF文件夹下面生成一个spring-configuration-metadata.json的文件。

内容如下


【工程结构】


CustomProperties

package com.artisan;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
 * @author 小工匠
 * @version 1.0
 * @description:  属性配置文件
 * @date 2021/5/22 18:56
 * @mark: show me the code , change the world
 */
@ConfigurationProperties("artisan.custom")
public class CustomProperties {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}



IndexController

package com.artisan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/5/22 18:58
 * @mark: show me the code , change the world
 */
@RestController
public class IndexController {
    private CustomProperties customProperties;
    public IndexController(CustomProperties customProperties) {
        this.customProperties = customProperties;
    }
    @RequestMapping("/")
    public String index() {
        return customProperties.getName();
    }
}

CustomAutoConfiguration 自动配置类

package com.artisan;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
 * @author 小工匠
 * @version 1.0
 * @description: 模拟给web应用自动添加一个首页
 * @date 2021/5/22 18:55
 * @mark: show me the code , change the world
 */
@Configuration
@ConditionalOnProperty(value = "artisan.custom.name")
@EnableConfigurationProperties(CustomProperties.class)
public class CustomAutoConfiguration {
    @Autowired
    CustomProperties cus;
    @Bean
    public IndexController indexController() {
        return new IndexController(cus);
    }
}



spring.factories

在 resources 下创建文件夹 META-INF 并在 META-INF 下创建文件 spring.factories ,内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.artisan.CustomAutoConfiguration

打包发布

到这儿,我们的配置自定义的starter就写完了 ,我们artisan-spring-boot-starter 和 artisan-spring-boot-starter-autoconfigurer 安装成本地jar包。


引用自定义starter测试

新建个spring boot 项目 ,引用刚才的starter

访问 http://localhost:8080/

咦 ,别忘了你自定义的属性

重启后,重新访问

因为我们开启了debug=true .找找我们自动装配的类看看


相关文章
|
9月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
788 2
|
10月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
7381 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
979 0
|
10月前
|
监控 安全 Java
使用 @HealthEndpoint 在 Spring Boot 中实现自定义健康检查
Spring Boot 通过 Actuator 模块提供了强大的健康检查功能,帮助开发者快速了解应用程序的运行状态。默认健康检查可检测数据库连接、依赖服务、资源可用性等,但在实际应用中,业务需求和依赖关系各不相同,因此需要实现自定义健康检查来更精确地监控关键组件。本文介绍了如何使用 @HealthEndpoint 注解及实现 HealthIndicator 接口来扩展 Spring Boot 的健康检查功能,从而提升系统的可观测性与稳定性。
718 0
使用 @HealthEndpoint 在 Spring Boot 中实现自定义健康检查
|
11月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1505 3
|
Java Maven 开发者
编写SpringBoot的自定义starter包
通过本文的介绍,我们详细讲解了如何创建一个Spring Boot自定义Starter包,包括自动配置类、配置属性类、`spring.factories`文件的创建和配置。通过自定义Starter,可以有效地复用公共配置和组件,提高开发效率。希望本文能帮助您更好地理解和应用Spring Boot自定义Starter,在实际项目中灵活使用这一强大的功能。
1229 17
|
JavaScript Java 程序员
SpringBoot自动配置及自定义Starter
Java程序员依赖Spring框架简化开发,但复杂的配置文件增加了负担。SpringBoot以“约定大于配置”理念简化了这一过程,通过引入各种Starter并加载默认配置,几乎做到开箱即用。
612 10
SpringBoot自动配置及自定义Starter
|
Java 数据库连接 Maven
最新版 | SpringBoot3如何自定义starter(面试常考)
在Spring Boot中,starter是一种特殊的依赖,帮助开发人员快速引入和配置特定功能模块。自定义starter可以封装一组特定功能的依赖和配置,简化项目中的功能引入。其主要优点包括模块化、简化配置、提高代码复用性和实现特定功能。常见的应用场景有短信发送模块、AOP日志切面、分布式ID生成等。通过创建autoconfigure和starter两个Maven工程,并编写自动配置类及必要的配置文件,可以实现一个自定义starter。最后在测试项目中验证其有效性。这种方式使开发者能够更便捷地管理和维护代码,提升开发效率。
2273 1
最新版 | SpringBoot3如何自定义starter(面试常考)