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