自定义starter Demo:
一、创建空项目
新建spring-boot-starter-demo(场景启动器,供别人使用)、spring-boot-starter-autoconfigure (功能配置,自动配置包)
spring-boot-starter-demo:只需引用autoconfigure工程
spring-boot-starter-autoconfigure:引入以下springboot相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置文件提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.4.2</version>
<optional>true</optional>
</dependency>
</dependencies>
autoconfigure中创建配置类:
@Configuration
@ConditionalOnMissingBean(HelloService.class)// 当容器中没有配置该类时,该配置类生效
@EnableConfigurationProperties(HelloProperties.class) // 开启属性文件绑定功能,默认HelloProperties放入容器中
public class HelloServiceAutoConfig {
@Bean
public HelloService helloService() {
HelloService helloService = new HelloService();
return helloService;
}
}
autoconfigure中业务逻辑:
/**
* 默认不要放在容器中
*/
public class HelloService {
@Autowired
private HelloProperties helloProperties;
public String sayHello(String userName) {
return helloProperties.getPrefix()+": "+userName+":" + helloProperties.getSuffix();
}
}
@ConfigurationProperties(prefix = "itheima.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;
}
}
autoconfigure中配置文件:
META-INF/spring.factorie:
# Auto Configure 项目启动自动启动该配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.itheima.starter.config.HelloServiceAutoConfig
测试案例:
在另一个springboot项目中引入上面的starter demo依赖项
<!-- 自定义starter场景启动器 -->
<dependency>
<groupId>com.itheima</groupId>
<artifactId>spring-boot-starter-demo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
在yml配置文件中配置我们在autoconfigure中的配置:
itheima:
hello:
prefix: 元顺帝
suffix: 努尔哈赤
controller:
@RestController
public class StarterController {
@Autowired
private HelloService helloService;
@RequestMapping("sayHello")
public String sayHello() {
String sayHello = helloService.sayHello("大明太祖 洪武 高皇帝 朱元章");
return sayHello;
}
}
starter启动原理
starter-pom引入 autoconfigurer 包
- autoconfigure包中配置使用 META-INF/spring.factories 中 EnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类
- 编写自动配置类 xxxAutoConfiguration -> xxxxProperties
-
- @Configuration
- @Conditional
- @EnableConfigurationProperties
- @Bean
- ......
引入starter --- xxxAutoConfiguration --- 容器中放入组件 ---- 绑定xxxProperties ---- 配置项
详细讲义:https://www.yuque.com/atguigu/springboot/tmvr0e
雷丰阳2021版SpringBoot2零基础入门springboot全套完整版(spring boot2)