spring boot(2.X)自定义 starter

148 阅读2分钟

1.   使用spring initializr 创建一个空白的spring boot项目,如test-spring-boot-starter

image.png

image.png

2. 创建完成后,你的idea可能由于某些原因导致没有把创建的项目当成一个maven项目,你需要手动添加一下,点击help,然后find action ,输入maven后找到add maven project,然后选择你的项目添加以下就可以

image.png

3.在pom.xml 加入以下依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>

4.在pom.xml 加入以下依赖管理

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.6.7</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
    </dependencies>
</dependencyManagement>

5.假如创建的starter需要使用到自定义的配置项,则创建包properties,并在下面创建一个配置类

@ConfigurationProperties("test")
public class TestProperties {
    
    private String version;
    
    public String getVersion() {
        return version;
    }
    
    public void setVersion(String version) {
        this.version = version;
    }
}

6.创建一个测试使用的业务类 ,创建包service,并在下面创建一个测试业务类

public class TestService {
    
    private final TestProperties testProperties;

    public TestService(TestProperties testProperties) {
        System.out.println("Test starter running ... ");
        this.testProperties = testProperties;
    }
    
    public void hello() {
        System.out.println("Hello world ... ");
    }
}

7.创建一个自动配置的核心类,spring boot会扫描这个类作为配置类

@Configuration
@ConditionalOnClass(TestService.class)
@EnableConfigurationProperties(TestProperties.class)
public class TestStartEnableAutoConfiguration {
    
    @Bean
    public TestService testService(TestProperties testProperties) {
        return new TestService(testProperties);
    }
}

8.在resources 文件下新建 META-INF,并新增文件spring.factories,写入以下内容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.riteny.config.TestStartEnableAutoConfiguration

9.以上步骤完成之后,点击maven->install,打包完成后,这个starter就会被安装到本地仓库

10.在starter安装到本地从仓库后,新建一个spring boot 项目,用于测试刚刚打包好的starter

在新创建的spring boot  依赖中假如

<dependency>  
    <groupId>com.riteny</groupId>  
    <artifactId>test-spring-boot-starter</artifactId>  
    <version>0.0.1-SNAPSHOT</version>  
</dependency>

在application.properties 中假如配置项

test.version=1.0.0

开发一个测试调用starter 服务方法hello的请求

@RestController  
@RequestMapping("/test")  
public class TestController {  

    @Autowired  
    private TestService testService;
    
    @GetMapping("/")  
    public void test(){  
        testService.hello();  
    }  
}

运行spring boot 后,首先可以看到日志中看到TestService 的输出

image.png 启动完成后,调用127.0.0.1:8080/test/,有以下输出

image.png 这样就证明自定义的starter已经正常运行