SpringBoot自定义启动类 starter
starter机制
SpringBoot中整合了很多的第三方依赖,使用起来只需要配置依赖和配置属性就可直接使用,非常方便。
我们在开发中可能会遇到一个模块多个场景重复使用的情况,这时就可以吧模块抽象出来,自定义成启动类,在配置文件中进行相关配置就可使用。
第一步 创建项目
创建两个项目(maven项目和SpringBoot项目),也可以创建一个空项目添加两个模块。
创建一个空项目
添加两个模块
一个为启动类maven项目 hancy-hello-spring-boot-starter
一个是自动配置的springboot项目 hancy-hello-spring-boot-starter-autoconfigure
第二步 修改pom.xml文件
hancy-hello-spring-boot-starter项目中添加以下配置
<dependencies>
<dependency>
<groupId>com.hancy</groupId>
<artifactId>hancy-hello-spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
hancy-hello-spring-boot-starter-autoconfigure 项目中添加以下配置(删除其他多余配置,尤其是test测试配置和插件配置,运行时可能会找不到依赖报错)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
第三步 编写配置类
1、编写配置文件类
@ConfigurationProperties(prefix = "hancy.hello") //启动配置文件
public class HelloProperties {
private String prefix;
private String suffix;
public HelloProperties() {
}
public HelloProperties(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = 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;
}
}
2、编写service文件,访问方法
public class HelloService {
@Autowired //自动注入配置文件类
HelloProperties helloProperties;
public String hello(String name){
return helloProperties.getPrefix() + ":" + name + helloProperties.getSuffix();
}
}
3、编写自动注入配置类
@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class) //启动配置类
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
public HelloServiceAutoConfiguration() {
}
@Bean
public HelloService helloService(){
return new HelloService();
}
}
第四步 编写resource目录下新建META-INF文件夹,在其下的spring.factories文件
此配置文件是springboot源码规定读取其中配置内容的自动配置项,想要通过配置文件配置,必须配置此文件。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.hancy.auto.HelloServiceAutoConfiguration (这里写全类名,有多个事,使用逗号,隔开)
第五步 将启动器模块,和自动配置模块install到仓库
先install自动配置,在install启动模块
第六步 在其他应用的pom.xml文件中添加启动器模块的依赖
<dependency>
<groupId>com.hancy</groupId>
<artifactId>hancy-hello-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
第七步 在配置文件中添加配置
hancy:
hello:
prefix: 你好呀!
suffix: 欢迎!
第八步 编写controller验证
@RestController
@RequestMapping("/test")
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String handle(){
return helloService.hello("hancy");
}
}