美文网首页
springboot自动配置、自定义starter/@Enabl

springboot自动配置、自定义starter/@Enabl

作者: quanCN | 来源:发表于2021-01-04 19:33 被阅读0次

    自定义starter

    • 自定义命名规则
      SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter命名规则。以区分SpringBoot生态提供的starter。
    • pom
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-configuration-processor</artifactId>
              <optional>true</optional>
          </dependency>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter</artifactId>
          </dependency>
      </dependencies>
      
    • 实体类映射配置信息
      @ConfigurationProperties(prefix = "demo")
      public class DemoProperties {
          private String mes;
          //Constructor
          //getter setter
      }
      
    • 定义一个Service
      //随便定义一个Service
      public class DemoService {
          private String mes;
          //Constructor
          //getter setter
      }
      
    • 配置类
      @Configuration
      @EnableConfigurationProperties(DemoProperties.class)//ioc注入
      public class DemoConfig {
          @Autowired
          private DemoProperties demoProperties;
      
          @Bean(name = "demo")
          public DemoService demoService(){
              return new DemoService(demoProperties.getMes());
          }
      }
      
    • src/main/resources/META-INF/spring.factories
      org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.lilq.cloudregistry.config.DemoConfig
      
    • test
      mvn clean install
      • pom
        <dependency>
            <groupId>cn.lilq</groupId>
            <artifactId>test-spring-boot-starter</artifactId>
            <version>0.1</version>
        </dependency>
        
      • application.properties
        demo.mes=hello
        
      • 测试类
        @Resource(name = "demo")
        private DemoService demoService;
        public String test(){
            return demoService.say();
        }
        

    带@EnableXXX开关的自动配置

    pom、实体类映射配置信息、Service、配置类不需要更改,且不需要spring.factories

    • EnableMyTest
      @Target(ElementType.TYPE)
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      @Inherited
      @Import(DemoConfig.class)
      @interface EnableMyTest {
      }
      

    相关文章

      网友评论

          本文标题:springboot自动配置、自定义starter/@Enabl

          本文链接:https://www.haomeiwen.com/subject/tdzvoktx.html