SprinigBoot自定义Starter
自定义Starter
是什么
starter可以理解是一组封装好的依赖包,包含需要的组件和组件所需的依赖包,使得使用者不需要再关注组件的依赖问题
所以一个staerter包含
- 提供一个autoconfigure类
- 提供autoconfigure类的依赖
怎么做
创建starter大概需要
- 需要一个配置类bean,来填充配置
- 获取配置信息,注册到容器
- 将配置类加到自动配置
导入自动装配和Spring boot依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
创建一个bean
@Data
public class HelloworldService {
private String words;
public String sayHello() {
return "hello, " + words;
}
}
创建peoperties类来自定义需要的参数,用来接收properties或者yml里的配置
//helloword就是配置的前缀
@ConfigurationProperties(prefix = "helloword")
public class HelloworldProperties {
public static final String DEFAULT_WORDS = "world";
//这个值就是helloword.words
private String words = DEFAULT_WORDS;
public String getWords() {
return words;
}
public void setWords(String words) {
this.words = words;
}
}
创建configureation类来注册bean
将配置的参数注入到bean里,在注册到容器
@Configuration
//指定条件成立的情况下自动配置类生效(往哪装配)
@ConditionalOnClass(HelloworldService.class)
//让xxxProperties生效加入到容器中
@EnableConfigurationProperties(HelloworldProperties.class)
public class HelloworldAutoConfiguration {
// 注入属性类
@Autowired
private HelloworldProperties hellowordProperties;
@Bean
// 当容器没有这个 Bean 的时候才创建这个 Bean
@ConditionalOnMissingBean(HelloworldService.class)
public HelloworldService helloworldService() {
HelloworldService helloworldService = new HelloworldService();
helloworldService.setWords(hellowordProperties.getWords());
return helloworldService;
}
}
在启动类里标明需要自动装配
@EnableAutoConfiguration//开启自动装配
@ComponentScan({"test"})
public class TestApplication {
}
最后是指定装配哪个配置类
在resources目录下创建META-INF
文件夹
然后创建spring.factories
标注需要装配的配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
test.config.HelloworldAutoConfiguration
最后就可以用这个starter了
首先导入这个starter
<dependency>
<groupId>org.example</groupId>
<artifactId>test-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
然后导入HelloworldService
这个bean
和在yml里配置参数
helloword:
words : hello
就完成了
本文来自博客园,作者:阿弱,转载请注明原文链接:https://www.cnblogs.com/aruo/p/15733194.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!