SpringBoot Starter的思想创建一个自己的SpringBoot Starter项目中引入自己的starter浏览器访问地址知其然知其所以然
SpringBoot的starter机制是如何运行的?关键流程解析 思考:为什么AutoConfigurationimportSelector要加载Spring.factories文件中的类进行配置?
SpringBoot Starter的思想一种约定大于配置的实现。引入starter相当于引入指定的功能,开箱即用依赖的管理方式,将一部分依赖已starter的方式一次性引入 创建一个自己的SpringBoot Starter
- 创建maven工程
引入依赖
org.springframework.boot spring-boot-autoconfigure2.5.4
- 创建基础DTO
public class Piano { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
- 创建提供服务的service
@Service public class PianoService { @Autowired private PianoProperties properties; public void playThePiano(String music) { System.out.println(properties.getPianist() + "d了一首" + music); } }
- 创建配置文件
@ConfigurationProperties(prefix = "zmj.piano") public class PianoProperties { private boolean enable; private String pianist; public boolean isEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } public String getPianist() { return pianist; } public void setPianist(String pianist) { this.pianist = pianist; } }
- 配置条件注入
@Configuration @ConditionalOnClass(PianoService.class) @ConditionalOnProperty(prefix = "zmj.piano", value = "enable", matchIfMissing = true) @EnableConfigurationProperties(PianoProperties.class) public class ZmjAutoConfiguration { @Bean @Order @ConditionalOnMissingBean public PianoService pianoService() { return new PianoService(); } }
- resources/meta-INF/spring.factories 增加配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration= org.zengmingjie.starter.ZmjAutoConfiguration
- 将项目install
mvn -Dmaven.test.skip=true clean install
- 此时在本地maven仓库就已经生成了jar包
- 引入starter
org.zengmingjie starterdemo0.0.1-SNAPSHOT
- 新建controller,引入PianoService
@RestController @RequestMapping("/test") public class TestController { @Autowired private PianoService pianoService; @GetMapping("/piano") public String piano(@RequestParam String music) { pianoService.playThePiano(music); return "success"; } }
- 配置application.yaml
zmj: piano: enable: true pianist: '贝多芬'浏览器访问地址
- ConfigurationClassPostProcessor.classAutoConfigurationimportSelector.class
https://blog.csdn.net/lemon89/article/details/79189475
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)