1. 新建springboot项目
注意:spring 官方提供 starter 通常命名为 spring-boot-starter-{name}, 我们自定义的starter一般命名为 {name}-spring-boot-starter
2. 删除启动类
3.修改pom文件
org.springframework.boot
spring-boot-configuration-processor
true
org.springframework.boot
spring-boot-autoconfigure
org.projectlombok
lombok
true
org.apache.maven.plugins
maven-compiler-plugin
4. 定义属性配置类
@Data
@ConfigurationProperties("test.example")
public class TestProperties {
private String host;
private int port;
}
5. 定义业务类
@Slf4j
public class TestService {
private String host;
private int port;
public TestService(TestProperties test){
this.host = test.getHost();
this.port = test.getPort();
}
public void print(){
log.info(this.host + ":" +this.port);
}
}
6. 定义配置类
@Configuration
@ConditionalOnClass(TestService.class)
@EnableConfigurationProperties(TestProperties.class)
@ConditionalOnProperty(prefix = "test.example",value = "enabled", havingValue = "true")
@Slf4j
public class TestAutoConfigure {
@Autowired
private TestProperties testProperties;
@Bean
@ConditionalOnMissingBean(TestProperties.class)
TestService testService(){
return new TestService(testProperties);
}
}
7. 在resources目录下新建meta-INF 目录,在下面新建 spring.factories 文件,文件中申明配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.baviya.testspringbootstarter.config.TestAutoConfigure
8.使用mvn clean install 打包
9. 项目中添加依赖
com.test test-spring-boot-starter1.0.0-SNAPSHOT
10. 在application文件中,定义属性,和上面的 属性配置类 TestProperties 关联
test:
example:
enabled: true
host: 127.0.0.1
port: 8080
12.在业务中使用
@RestController
@RequestMapping
@Slf4j
public class TestController {
@Autowired
private TestService testService;
@RequestMapping
public String test(HttpServletRequest request){
testService.print();
}
}
1. 遇到的问题:Unable to read meta-data for class XXXXX
是因为没有删除启动类导致,删除重新打包即可
2. 删除启动类打包失败
修改pom文件中build模块
org.apache.maven.plugins maven-compiler-plugin



