天天看點

飛5的Spring Boot2(4)- 自定義starter

飛5的Spring Boot2(4)- 自定義starter

自定義starter​

在業務中,我們經常需要一些常用的工具包,現在,有了Spring Boot,我們可以使用starter的方式引入。

建立maven工程,在pom.xml中加入Spring Boot依賴

1<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->
2        <dependency>
3            <groupId>org.springframework.boot</groupId>
4            <artifactId>spring-boot</artifactId>
5            <version>2.0.1.RELEASE</version>
6        </dependency>      

由于starter項目需要使用到spring的一些特性,是以在starter項目中至少需要依賴一個對org.springframework.boot的依賴。

三步建構

第一步

建立一個maven項目user-starter,建立UserService類,代碼如下:

1public class UserService {
2    public void helloStarter(){
3        System.out.println(">> hello starter");
4    }
5}      

第二步

建立一個UserAutoConfiguration類,代碼如下:

1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3@Configuration
4public class UserAutoConfiguration {
5    @Bean
6    public UserService dbCountRunner() {
7        return new UserService();
8    }
9}      

加入配置

在resources目錄中建立META-INF檔案夾,然後在META-INF檔案夾中建立spring.factories檔案==,這個檔案用于告訴spring boot去找指定的自動配置檔案。在應用程式啟動過程中,spring boot使用springfactoriesloader類加載器查找org.springframework.boot.autoconfigure.enableautoconfiguration關鍵字對應的java配置檔案。spring boot會周遊在各個jar包種meta-inf目錄下的spring.factories檔案,建構成一個配置檔案連結清單。

spring.factories内容如下:

1org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.cloud.skyme.UserAutoConfiguration      

加入依賴

在項目中進行依賴

1<dependency>
2    <groupId>com.eju.ess</groupId>
3    <artifactId>user-starter</artifactId>
4    <version>0.0.2-SNAPSHOT</version>
5</dependency>      
1import org.springframework.beans.factory.annotation.Autowired;
 2import org.springframework.web.bind.annotation.RequestMapping;
 3import org.springframework.web.bind.annotation.RestController;
 4import com.cloud.skyme.UserService;
 5import lombok.extern.slf4j.Slf4j;
 6@Slf4j
 7@RestController
 8public class SampleController {
 9    @Autowired
10    private UserService t=null;
11    @RequestMapping("/")
12    String home() {
13        t.helloStarter();
14        return "Hello World!";
15    }
16}      

繼續閱讀