springboot如何自定义starter
1.自定義啟動器
lmh-hello-spring-boot-starter(啟動器)
lmh-hello-spring-boot-starter-autoconfigure(自動配置包)
1.1 創建一個空項目
1.2 在空項目的基礎上,添加maven空項目,項目名稱叫做
lmh-hello-spring-boot-starter
再添加一個springboot空項目,項目名稱lmh-hello-spring-boot-starter-autoconfigure
1.3 lmh-hello-spring-boot-starter(啟動器)的pom.xml文件中,將lmh-hello-spring-boot-starter-autoconfigure的groupId和artifactId作為依賴添加進去
1.4 注意每個類所在路徑
創建HelloService類,業務處理的過程
創建HelloProperties類
@ConfigurationProperties("lmh.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;} }創建HelloServiceAutoConfiguration類
@Configuration @ConditionalOnMissingBean(HelloService.class) //當容器中沒有HelloService組件時,下面才生效 @EnableConfigurationProperties(HelloProperties.class) // 默認放在容器中 public class HelloServiceAutoConfiguration {@Beanpublic HelloService helloService(){HelloService helloService = new HelloService();return helloService;}}創建spring.factories
# Auto configure 啟動時,就開始加載 HelloServiceAutoConfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.example.auto.HelloServiceAutoConfiguration1.5 將啟動器和配置包 先clean,再install添加到maven倉庫中![在這里
1.6 使用
在新項目中,添加啟動器的依賴
application.properties中
lmh.hello.prefix=username lmh.hello.suffix=77777創建HelloController類
@RestController public class HelloController {@AutowiredHelloService helloService;@GetMapping("/hello")public String sayHello(){String s = helloService.sayHello("李白");return s;} }1.7 地址訪問
localhost:8080/hello
2.starter啟動原理
starter—> autoConfigure—>spring-boot-starter
autoconfigure包中配置使用META-INF/spring.factories 中EnableAutoConfiguration的值,使項目啟動加載指定的自動配置類
編寫自動配置類 xxxAutoConfiguration --> xxxProperties
- @ConfigurationProperties(“lmh.hello”)
- @Configuration
- @ConditionalOnMissingBean(HelloService.class) //當容器中沒有HelloService組件時,下面才生效
- @EnableConfigurationProperties(HelloProperties.class) // 默認放在容器中
- @Bean 組件
- …
總結
以上是生活随笔為你收集整理的springboot如何自定义starter的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单对比4G的两种模式
- 下一篇: 精力管理--分享感悟