自定义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(); }
- pom
带@EnableXXX开关的自动配置
pom、实体类映射配置信息、Service、配置类不需要更改,且不需要spring.factories
- EnableMyTest
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(DemoConfig.class) @interface EnableMyTest { }
网友评论