手写一个Spring Boot Starter
最后更新于
这有帮助吗?
最后更新于
这有帮助吗?
创建一个maven项目 hello-spring-boot-starter
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
创建 HelloProperties
, HelloService
, HelloAutoConfiguration
// HelloProperties.java
// ConfigurationProperties只有在EnableConfigurationProperties显示开启时才生效
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// HelloService的实现类 HelloServiceImpl.java
public class HelloServiceImpl implements HelloService {
@Resource
private HelloProperties helloProperties;
public String sayHello() {
System.out.println("hello, " + helloProperties.getName());
return "";
}
}
// HelloAutoConfiguration.java
@Configuration
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(HelloProperties.class)
@ConditionalOnClass(HelloService.class)
public class HelloAutoConfiguration {
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService() {
return new HelloServiceImpl();
}
}
在resources目录下添加 spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.HelloAutoConfiguration
整体目录结构如下,已完成基本的开发工作
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── org
│ │ │ └── example
│ │ │ ├── HelloAutoConfiguration.java
│ │ │ ├── HelloProperties.java
│ │ │ └── service
│ │ │ ├── HelloService.java
│ │ │ └── impl
│ │ │ └── HelloServiceImpl.java
│ │ └── resources
│ │ └── META-INF
│ │ └── spring.factories
mvn install 安装到本地maven仓库进行测试
spring-boot-web 测试模块引入依赖
<dependency>
<groupId>org.example</groupId>
<artifactId>hello-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>