SpringBoot之starter
简介
Spring Boot Starter 是 Spring Boot 框架中的一个核心概念,它是一种用于简化 Spring 应用程序配置和依赖管理的机制。Spring Boot Starter 可以理解为预定义了特定功能或集成的依赖模块集合,通过引入这些 Starter,可以快速构建和配置应用程序,而无需手动处理大量的依赖和配置。
编写SpringBoot的starter
1.引入Maven依赖
<!-- 提供starter的主要依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 提供获取配置信息的类 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
注意事项
在idea中可以只加入前两个依赖,就可以完成starter的编写。
spring-boot-configuration-processor的主要作用是提供发现配置。很多次idea中编写yaml没有提示,就是由于编写starter时没有加入此依赖。
2.编写properties
@Component
@ConfigurationProperties(prefix = "starter.test")
public class TestProperties {
private String message = "test";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
properties的主要作用就是将开发时yml的配置信息映射到此类上
3.编写业务代码
public class TestService {
private final TestProperties properties;
public TestService(TestProperties properties) {
this.properties = properties;
}
public void print(){
System.out.println(properties.getMessage());
}
}
4.编写配置类
@Configuration
@ConditionalOnClass(TestService.class)
@EnableConfigurationProperties(TestProperties.class)
public class TestConfiguration {
private final TestProperties testProperties;
public TestConfiguration(TestProperties testProperties) {
this.testProperties = testProperties;
}
@Bean
@ConditionalOnMissingBean
public TestService testService(){
return new TestService(testProperties);
}
}
- @ConditionalOnClass 注解:
@ConditionalOnClass(TestService.class)
意味着该配置类的生效条件是当前项目的 classpath 中存在TestService
类。只有当TestService
类被加载到类路径中时,TestConfiguration
才会被实例化和应用。
- @EnableConfigurationProperties 注解:
@EnableConfigurationProperties(TestProperties.class)
用于启用特定的配置属性类TestProperties
,使得该类能够被 Spring Boot 管理,并且可以通过依赖注入的方式在其他组件中使用。
- @ConditionalOnMissingBean 注解:
@ConditionalOnMissingBean
表示当容器中不存在TestService
类型的 Bean 时,才会创建并注册这个 Bean。这保证了如果用户已经定义了TestService
的 Bean,那么这个默认的TestService
不会被覆盖。
5.编写spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.quick.config.TestConfiguration
需要在resource文件夹下新建文件夹META-INF中创建spring.factories
在这个文件中,可以声明自动配置类的路径,这些自动配置类会在应用启动时根据需要自动生效
6.编译成jar包
使用maven的打包即可
下新建文件夹META-INF中创建spring.factories
在这个文件中,可以声明自动配置类的路径,这些自动配置类会在应用启动时根据需要自动生效
6.编译成jar包
使用maven的打包即可