• Spring Boot如何自定义自己的Starter组件?


    一、为什么要自定义starter

    在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的 包下,然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一 遍,麻烦至极。如果我们将这些可独立于业务代码之外的功能配置模块封装成一个个starter,复用的时 候只需要将其在pom中引用依赖即可,SpringBoot为我们完成自动装配,简直不要太爽。

    二、starter的实现

    虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationPropertiesAutoConfiguration。因为Spring Boot坚信“约定大于配置”这一理念,所以我们使用ConfigurationProperties来保存我们的配置,并且这些配置都可以有一个默认值,即在我们没有主动覆写原始配置的情况下,默认值就会生效,这在很多情况下是非常有用的。除此之外,starterConfigurationProperties还使得所有的配置属性被聚集到一个文件中(一般在resources目录下的application.properties),这样我们就告别了Spring项目中XML地狱。

    三、命名规范

    如果你快有孩子了,出生前你比较急的一定是起个名字。孩子的姓名标识着你和你爱人的血统,一定不会起隔壁老王的姓氏,肯定会招来异样的眼光。在maven中,groupId代表着姓氏,artifactId代表着名字。Spring Boot也是有一个命名的建议的。所以名字是不能够随随便便取得,可以按照官方的建议来取。

    What’s in a name All official starters follow a similar naming pattern; spring-boot-starter-  , where is a particular type of application. This naming structure is intended to help when you need to find a starter. The Maven integration in many IDEs lets you search dependencies by name. For example, with the appropriate Eclipse or STS plugin installed, you can press ctrl-space in the POM editor and type “spring-boot-starter” for a complete list. As explained in the “Creating Your Own Starter” section, third party starters should not start with spring-boot, as it is reserved for official Spring Boot artifacts. Rather, a third-party starter typically starts with the name of the project. For example, a third-party starter project called thirdpartyproject would typically be named thirdpartyproject-spring-boot-starter.

    大概意思:官方的 starter 的命名格式为 spring-boot-starter-{xxxx} 比如spring-boot-starter-activemq,第三方我们自己的命名格式为 {xxxx}-spring-boot-starter。比如mybatis-spring-boot-starter。如果我们忽略这种约定,是不是会显得我们写的东西不够“专业“。

    四、代码工程

    pom.xml

     
     
    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <parent>
    6. <artifactId>springboot-demoartifactId>
    7. <groupId>com.etgroupId>
    8. <version>1.0-SNAPSHOTversion>
    9. parent>
    10. <modelVersion>4.0.0modelVersion>
    11. <artifactId>xxx-spring-boot-starterartifactId>
    12. <properties>
    13. <maven.compiler.source>8maven.compiler.source>
    14. <maven.compiler.target>8maven.compiler.target>
    15. properties>
    16. <dependencies>
    17. <dependency>
    18. <groupId>org.springframework.bootgroupId>
    19. <artifactId>spring-boot-autoconfigureartifactId>
    20. dependency>
    21. <dependency>
    22. <groupId>org.springframework.bootgroupId>
    23. <artifactId>spring-boot-configuration-processorartifactId>
    24. <optional>trueoptional>
    25. dependency>
    26. dependencies>
    27. project>

    属性文件

     
     
    1. com.person.age=23
    2. com.person.name=Lynch
    3. com.person.sex=F

    自动配置类

     
     
    1. package com.et.config;
    2. import com.et.service.PersonService;
    3. import com.et.starter.PersonProperties;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    6. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    7. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    8. import org.springframework.boot.context.properties.EnableConfigurationProperties;
    9. import org.springframework.context.annotation.Bean;
    10. import org.springframework.context.annotation.Configuration;
    11. @Configuration
    12. @EnableConfigurationProperties(PersonProperties.class)
    13. @ConditionalOnClass(PersonService.class)
    14. @ConditionalOnProperty(prefix = "com.person", value = "enabled", matchIfMissing = true)
    15. public class PersonServiceAutoConfiguration {
    16. @Autowired
    17. private PersonProperties properties;
    18. // if spring container do not config bean,auto config PersonService
    19. @Bean
    20. @ConditionalOnMissingBean(PersonService.class)
    21. public PersonService personService(){
    22. PersonService personService = new PersonService(properties);
    23. return personService;
    24. }
    25. }

    service类

     
     
    1. package com.et.service;
    2. import com.et.starter.PersonProperties;
    3. public class PersonService {
    4. private PersonProperties properties;
    5. public PersonService() {
    6. }
    7. public PersonService(PersonProperties properties) {
    8. this.properties = properties;
    9. }
    10. public void sayHello() {
    11. String message = String.format("hi,my name: %s, today,I'am %s , gender: %s",
    12. properties.getName(), properties.getAge(), properties.getSex());
    13. System.out.println(message);
    14. }
    15. }

    PersonProperties

     
     
    1. package com.et.starter;
    2. import java.io.Serializable;
    3. import org.springframework.boot.context.properties.ConfigurationProperties;
    4. @SuppressWarnings("serial")
    5. @ConfigurationProperties(prefix = "com.person")
    6. public class PersonProperties implements Serializable {
    7. private String name;
    8. private int age;
    9. private String sex = "M";
    10. public PersonProperties() {
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public int getAge() {
    19. return age;
    20. }
    21. public void setAge(int age) {
    22. this.age = age;
    23. }
    24. public String getSex() {
    25. return sex;
    26. }
    27. public void setSex(String sex) {
    28. this.sex = sex;
    29. }
    30. }

    spring.factories文件

    /META-INF/spring.factories文件放在/src/main/resources目录下 注意:META-INF是自己手动创建的目录,spring.factories也是自己手动创建的文件,在该文件中配置自己的自动配置类。

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.et.config.PersonServiceAutoConfiguration

    项目打包

    mvn clean install

    代码仓库

    • https://github.com/Harries/springboot-demo

    五、测试

    在另外一个项目中添加starter的依赖

     
     
    1. <dependency>
    2. <groupId>com.etgroupId>
    3. <artifactId>xxx-spring-boot-starterartifactId>
    4. <version>1.0-SNAPSHOTversion>
    5. dependency>

    单元测试类

     
     
    1. package com.et.starter;
    2. import com.et.service.PersonService;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.boot.test.context.SpringBootTest;
    7. import org.springframework.test.context.junit4.SpringRunner;
    8. @RunWith(SpringRunner.class)
    9. @SpringBootTest
    10. public class PersonServiceTest {
    11. @Autowired
    12. private PersonService personService;
    13. @Test
    14. public void testHelloWorld() {
    15. personService.sayHello();
    16. }
    17. }

    运行测试类

    1. 2024-03-11 10:35:18.374 INFO 10960 --- [ main] com.et.starter.PersonServiceTest : Starting PersonServiceTest on BJDPLHHUAPC with PID 10960 (started by Dell in D:\IdeaProjects\ETFramework\xxx-spring-boot-starter-test)
    2. 2024-03-11 10:35:18.376 INFO 10960 --- [ main] com.et.starter.PersonServiceTest : No active profile set, falling back to default profiles: default
    3. 2024-03-11 10:35:19.387 INFO 10960 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
    4. 2024-03-11 10:35:19.657 INFO 10960 --- [ main] com.et.starter.PersonServiceTest : Started PersonServiceTest in 1.507 seconds (JVM running for 2.188)
    5. hi,my name: Lynch, today,I'am 23 , gender: F
    6. 2024-03-11 10:35:19.827 INFO 10960 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

    六、引用

    • https://www.cnblogs.com/linjiqin/p/13436943.html

    • http://www.liuhaihua.cn/archives/710303.html

    93bac648e90847c6f9b790c3da0e8ab7.jpeg

  • 相关阅读:
    自动化测试框架Pytest(三)——自定义allure测试报告
    Docker和K8S的区别
    C# 使用base64编码用于加密和解密
    VirtIO
    java处理异常这一篇就够了
    sql注入学习笔记
    (数据结构)算法的时间复杂度
    2015-2023_个人工作总结
    Google Earth Engine(GEE)——landsat 8 去云一个简单的ui.select()结果
    很可惜,pyinstaller不是万能的
  • 原文地址:https://blog.csdn.net/dot_life/article/details/136639313