springboot自定义starter

命名规范:
spring官方starter通常命名为spring-boot-starter-{name}, 如:spring-boot-starter-web
spring官方建议非官方starter命名应遵循{name}-spring-boot-starter的格式, 如:mybatis-spring-boot-starter

maven

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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>org.example</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>1.0.0</version>

<dependencies>
<!-- 自定义starter的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.7.18</version>
</dependency>
<!-- 配置属性在idea中提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.7.18</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>

创建获取配置文件属性的类

1
2
3
4
5
6
7
@ConfigurationProperties("starter")
public class StarterProperties {

private String name;

// getter setter ...
}

创建测试类

1
2
3
4
5
6
7
8
9
10
11
12
public class StarterService {

private final StarterProperties starterProperties;

public StarterService(StarterProperties starterProperties) {
this.starterProperties = starterProperties;
}

public String getName() {
return this.starterProperties.getName();
}
}

创建自动装配bean的配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableConfigurationProperties(StarterProperties.class)
public class StarterConfiguration {

private final StarterProperties starterProperties;

public StarterConfiguration(StarterProperties starterProperties) {
this.starterProperties = starterProperties;
}

@Bean
public StarterService starterService() {
return new StarterService(starterProperties);
}
}

创建spring.factories

没有此文件配置,自动配置类不会生效。将创建的配置类路径填写到里面。
此文件需要自己手动创建,位置:src/main/resources/META-INF/spring.factories

1
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.StarterConfiguration

测试

将上面的项目mvn install并引入到测试项目中

  1. 配置

    1
    2
    starter:
    name: hello
  2. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @SpringBootTest
    public class MyTests {

    @Autowired
    StarterService starterService;

    @Test
    public void test(){
    System.out.println(starterService.getName());
    }
    }