本文最后更新于:2024年9月8日 晚上
Spring Boot 自定义Starter
概述
启动器模块是一个空 jar 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库。
命名规约
编写启动器
- 在IDEA中新建一个空项目
spring-boot-starter-diy
- 新建一个普通Maven模块
test-spring-boot-starter
- 新建一个Spring Boot模块
test-spring-boot-starter-autoconfigure
- 点击apply即可,基本结构。
- 在我们的 starter模块中导入 autoconfigure 的依赖。
1 2 3 4 5
| <dependency> <groupId>com.test</groupId> <artifactId>test-spring-boot-starter-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
|
- 将 autoconfigure 项目下多余的文件都删掉,
Pom.xml
中只留下一个spring-boot-starter
,这是所有的启动器基本配置。
- 编写一个自定义的服务类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class HelloService {
HelloProperties helloProperties;
public HelloProperties getHelloProperties() { return helloProperties; }
public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; }
public String sayHello(String name){ return helloProperties.getPrefix() + name + helloProperties.getSuffix(); }
}
|
- 编写HelloProperties配置类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
@ConfigurationProperties(prefix = "test.hello") public class HelloProperties {
private String prefix; private String suffix;
public String getPrefix() { return prefix; }
public void setPrefix(String prefix) { this.prefix = prefix; }
public String getSuffix() { return suffix; }
public void setSuffix(String suffix) { this.suffix = suffix; } }
|
- 编写自定义的自动配置类并注入bean,测试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Configuration @ConditionalOnWebApplication @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration {
@Autowired HelloProperties helloProperties;
@Bean public HelloService helloService(){ HelloService service = new HelloService(); service.setHelloProperties(helloProperties); return service; }
}
|
- 在resources编写一个自己的
META-INF\spring.factories
1 2 3
| org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.test.HelloServiceAutoConfiguration
|
- 编写完成后,可以安装到maven仓库中。
测试启动器
- 新建一个Spring Boot 项目。
- 导入我们自己写的启动器。
1 2 3 4 5
| <dependency> <groupId>com.test</groupId> <artifactId>test-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
|
- 编写一个 HelloController 进行测试我们自己的写的接口。
1 2 3 4 5 6 7 8 9 10 11 12
| @RestController public class HelloController {
@Autowired HelloService helloService;
@RequestMapping("/hello") public String hello(){ return helloService.sayHello("zxc"); }
}
|
- 编写配置文件
application.properties
1 2
| test.hello.prefix="aaa" test.hello.suffix="bbb"
|
- 启动项目进行测试,结果成功。