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

自定义starter

  • 自定义命名规则
    SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter命名规则。以区分SpringBoot生态提供的starter。
  • pom
    
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
            org.springframework.boot
            spring-boot-starter
        
    
    
  • 实体类映射配置信息
    @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
      
          cn.lilq
          test-spring-boot-starter
          0.1
      
      
    • 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/@EnableXXX)