spring自定義一個簡單的Starter啟動器
思路
1、導入Spring的依賴
2、創(chuàng)建類完成相關邏輯(starter的意義就是生成一系列對象,讓我們可以進行注入)
3、定義配置類完成Bean的初始化
4、設置spring.factories配置文件(原理如下)
實操:
1、創(chuàng)建項目
這個命名只是簡單命名的,正式定義starter還是以 spring-boot-starter-xxx 的方式命名的。
2、導入Spring的關鍵必要的依賴(想額外完成什么功能就導什么依賴)
<parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.4.5</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--注解處理器:生成配置元數(shù)據(jù)--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies>
3、創(chuàng)建類完成相關邏輯
package com.test.MyCode; public class HelloWorld { public String sayHello(){ return "helloWord"; } }
4、定義配置類完成Bean的初始化
package com.test.config; import com.test.MyCode.HelloWorld; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HelloWordConfiguration { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } }
5、設置spring.factories配置文件
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.test.config.HelloWordConfiguration
6、打包安裝即可,導入依賴即可使用
關于starter啟動類的原理:
① Spring Boot 在啟動時會去classpath中尋找 resources/META-INF/spring.factories 文件,配置文件格式是key==value,value中配置了很多需要Spring加載的類
② 根據(jù) spring.factories 配置加載 AutoConfigure 類
③ 根據(jù) @Conditional 注解的條件,進行自動配置并將 Bean 注入 Spring Context
到此這篇關于spring自定義一個簡單的Starter啟動器的文章就介紹到這了,更多相關spring自定義Starter內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring應用中使用acutator/refresh刷新屬性不生效的問題分析及解決
在Spring應用收到/actuator/refresh的POST請求后,標注了@RefreshScope以及@ConfiguratioinProperties的bean會被Spring容器重新加載,但是,在實際應用中,并沒有按照預期被Spring容器加載,本文將討論導致這種未按預期刷新的一種原因,感興趣的朋友可以參考下2024-01-01Java使用try-with-resources實現(xiàn)自動解鎖
項目中使用Redission分布式鎖,每次使用都需要顯示的解鎖,很麻煩,Java 提供了 try-with-resources 語法糖,它不僅可以用于自動關閉流資源,還可以用于實現(xiàn)自動解鎖,本文將介紹如何利用 try-with-resources 實現(xiàn)鎖的自動釋放,需要的朋友可以參考下2025-01-01