javascript
SpringBoot 自定义starter 保姆级教程(说明+源码+配置+测试)
1.說明
命名歸約-官方命名:
前綴:spring-boot-starter-xxx(比如:spring-boot-starter-web)
命名歸約-自定義命名:
xxx-spring-boot-starter(比如:mybatis-spring-boot-starter)可憐的mybatis。
2.編寫啟動器
1、在IDEA中新建一個空項目 java-spring-boot-starter
2、新建一個普通Maven模塊:my-spring-boot-starter
3、新建一個Springboot模塊:my-spring-boot-starter-autoconfigure
4、點擊apply即可,基本結(jié)構(gòu)
5、在 starter 中 導(dǎo)入 autoconfigure 的依賴
6、將 autoconfigure 項目下多余的文件都刪掉,Pom中只留下一個 starter,這是所有的啟動器基本配置
7、編寫一個自己的服務(wù)
8、編寫HelloProperties 配置類
package com.example; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "my.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;} }9、編寫自動配置類并注入bean,測試
package com.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnWebApplication @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration {@AutowiredHelloProperties helloProperties;@Beanpublic HelloService helloService(){HelloService service = new HelloService();service.setHelloProperties(helloProperties);return service;} }10、在resources編寫一個自己的 META-INF\spring.factories
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.kuang.HelloServiceAutoConfiguration11、編寫完成后,可以安裝到maven倉庫中,看一下最終的結(jié)構(gòu):
3.測試
1、新建一個SpringBoot 項目
2、導(dǎo)入我們自己寫的啟動器
3、編寫一個 HelloController 進行測試我們自己的寫的接口!
package com.example.controller; import com.example.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController {@AutowiredHelloService helloService;@RequestMapping("/hello")public String hello() {return helloService.sayHello("-my-");} }4、編寫配置文件 application.properties
my.hello.prefix="hello" my.hello.suffix="starter"5、啟動項目進行測試,結(jié)果成功 !
總結(jié)
以上是生活随笔為你收集整理的SpringBoot 自定义starter 保姆级教程(说明+源码+配置+测试)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot 项目war包部署
- 下一篇: Neo4j【环境部署 01】图形数据库(