springboot系列十4、自定義實現starter

1、starter的做用

  當咱們實現了一個組建,但願儘量下降它的介入成本,通常的組建寫好了,只要添加spring掃描路徑加載spring就能發揮做用。有個更簡單的方式掃描路徑都不用加,直接引入jar就能使用。java

  原理時由於springboot提供一個配置文件 spring.factories,預約好了加載那個配置類。web

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xjw.HelloAutoConfiguration

2、自定義實現starter

一、建立pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>generateCode-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>generateCode-starter</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

二、建立配置類

package com.starter.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GeneraterConfig {

    @Bean
    GeneraterIdService getGeneraterIdService(){
        return new GeneraterIdService();
    }

}

三、組建類:GeneraterIdService.java

package com.starter.demo;

import java.util.Date;

public class GeneraterIdService {
    public String generaterId(){
        return new Date().getTime()+"";
    }
}

四、spring.factories文件

路徑:resources/META-INF/spring.factoriesspring

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.starter.demo.GeneraterConfig

3、打包測試

一、引入

<dependency>
    <groupId>com.example</groupId>
    <artifactId>generateCode-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

二、使用測試

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class RestTemplateTest {
    @Autowired
    GeneraterIdService generaterIdService;

    @Test
    public void TestGeneraterId(){
        System.out.println(generaterIdService.generaterId());
    }

}
相關文章
相關標籤/搜索