# basic-spring-boot-starter **Repository Path**: tedfang/basic-spring-boot-starter ## Basic Information - **Project Name**: basic-spring-boot-starter - **Description**: 练习starter的仓库 - **Primary Language**: Java - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-08-05 - **Last Updated**: 2021-08-05 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 练习starter的仓库 ### 1.引入两个包 ### 2.spring.factories - resource/META-INF 目录下创建名称为 spring.factories 的文件 - 当 Spring Boot 启动的时候,会在 classpath 下寻找所有名称为 spring.factories 的文件, 然后运行里面的配置指定的自动加载类,将指定类(一个或多个)中的相关 bean 初始化 - org.springframework.boot.autoconfigure.EnableAutoConfiguration=DemoConfig - 等号前面是固定的写法,后面就是我们自定义的自动配置类了,如果有多个的话,用英文逗号分隔开。 ### 3.编写自动配置类 DemoConfig.java ```javascript @Configuration @EnableConfigurationProperties(DemoProperties.class) @ConditionalOnProperty(name = "tedfang.demo.enabled",havingValue = "true",matchIfMissing = true) ``` ``` @ConditionalOnClass(Demo.class) - 只有在classpath中找到Demo类的情况下,才会解析此自动配置类,否则不解析 @ConditionalOnMissingBean(Demo.class) - 与@Bean配合使用,只有在当前上下文中不存在某个bean的情况下才会执行所注解的代码块,也就是当前上下文还没有Demo的bean实例的情况下,才会执行Demo()方法,从而实例化一个bean实例出来 @ConditionalOnProperty - 当应用配置文件中有相关的配置才会执行其所注解的代码块 ``` ### 4.mvn install 打包到本地仓库 ### 5.在新项目里引入并且在application.yml进行配置 ``` cn.tedfang basic-spring-boot-starter 1.4 ``` ``` tedfang: demo: enabled: true say-what: hello to-who: shf ``` ```java package cn.fang.modules.demo; import cn.tedfang.DemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @Author tedfang * @Date 2021/8/3. */ @RestController public class DemoController { //@Autowired //private DemoService demoService; @Resource(name = "starterDemo") private DemoService demoService; @GetMapping("/sys/log/say") public String sayWhat(){ return demoService.say(); } } ```