SpringBoot - 自定义模块 starter
本节学习自定义SpringBoot模块starter的步骤和注意事项。
本节详细代码:dyj123-hello-springboot-custom-starter - adas5f1a51/GitHub
1. 为什么要自定义模块 starter
传统方式使用 Spring 开发项目,需要编写一大堆配置文件,引入很多依赖。久而久之配置文件维护难度加大,依赖引入难于控制(被戏称为“依赖地狱”),加重了开发人员的负担。
为此 Spring 推出了 Spring Boot 用来简化开发,Spring Boot 的核心就是使用各种模块的 starter(又称启动器)来进行配置参数,依赖导入等功能的自动化。
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.
Spring Boot - spring.io
在开发过程中,对于某些常用的代码或功能,我们可以抽取出来,编写我们自定义模块的 starter 来实现这些功能,帮助我们使得开发更简单更有效率。
2. 简述模块 starter 原理
starter 启动器包只是负责引入依赖,并没有实际代码。真正实现自动配置功能的是 autoconfigure 自动配置包以及我们需要抽取的代码。
细节:
- starter 启动器包负责引入 autoconfigure 自动配置包和我们需要抽取的代码包;
- autoconfigure 自动配置包编写自动配置类和配置参数类,并引入相关依赖;
- autoconfigure 自动配置包需要编写
spring.factories
配置文件,以让Spring读取并使用自定义 starter 。
3. 编写自定义模块 starter
需要编写以下包:
- 我们需要抽取的代码包;
- autoconfigure 自动配置包;
- starter 启动器包。
3.1 代码包
代码包负责将我们需要抽取的代码封装好。
我以访问一个请求能接收一段文字这个功能编写代码。
控制器:
@RestController
public class HelloController {
private HelloService service;
@Autowired // 自动注入
public void setService(HelloService service) {
this.service = service;
}
@GetMapping("/hello")
public String sayHello() {
return service.sayHello();
}
}
业务逻辑:
// 通过自动配置类注册到容器
public class HelloServiceImpl implements HelloService {
private final String message;
// 通过构造器注入
public HelloServiceImpl(String message) {
this.message = message;
}
@Override
public String sayHello() {
return message;
}
}