1. 新建springboot项目
注意:spring 官方提供 starter 通常命名为 spring-boot-starter-{name}, 我们自定义的starter一般命名为 {name}-spring-boot-starter
2. 删除启动类
3.修改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-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<build>
<!-- 这里是普通的maven plugin 不然会报错,因为没有启动类,-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
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. 项目中添加依赖
<dependency>
<groupId>com.test</groupId>
<artifactId>test-spring-boot-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
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模块
<build>
<!-- 这里是普通的maven plugin 不然会报错,因为没有启动类,-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>