spring boot自動設定實現

來源:互聯網
上載者:User

標籤:mis   context   一起   設定檔   red   jar包   大於   實現   color   

自從用了spring boot,都忘記spring mvc中的xml配置是個什麼東西了,再也回不去。為啥spring boot這麼好用呢, 約定大於配置的設計初衷, 讓我們只知道維護好application.properties(或application.yml)檔案就可以了,我們在設定檔裡可以設定資料來源參數,可以設定服務連接埠,可以設定redis的地址等等。我們經常會看一些包含starter名字的jar包,如spring-boot-starter-data-redis,引入這些jar包,我們就可以簡單快速配置了。那麼我們自己開發了一個介面服務給別人調用,我們是不是可以把它封裝成一個starter jar包呢?讓別人在application.properties定義,實現自動設定呢?答案是允許的,下面跟我一起寫一個自動設定jar包。(本文的目的不是講解自動設定的原理,大家可以自行網上搜尋原理)。

  1. 環境資訊

    開發工具:idea

    maven版本號碼:3.5.4

  2. jar包封裝

    建立一個springboot項目

    填寫座標資訊

    springboot版本2.0.4

    其他預設,建立完成後,目錄如下

    接下來建立我們的測試服務類TestService

     1 package com.tanghuachun.teststarter; 2  3 public class TestService { 4  5     private String ip; 6     private int port; 7  8     public TestService(String ip, int port){ 9         this.ip = ip;10         this.port = port;11     }12     13     public void printConfInfo(){14         System.out.println("騷年,你配置的IP為:" + ip + ",連接埠為:" + port);15     }16 }

    我們設想,別人使用我們這個介面的時候,將Ip和Port通過application.properties注入,接下來我們建立屬性配置實體類TestServiceProperties

     1 package com.tanghuachun.teststarter; 2  3 import org.springframework.boot.context.properties.ConfigurationProperties; 4  5 @ConfigurationProperties(prefix = "test-config")//取設定檔首碼為test-config配置 6 public class TestServiceProperties { 7     private String host; 8     private int port; 9 10     public String getHost() {11         return host;12     }13 14     public void setHost(String host) {15         this.host = host;16     }17 18     public int getPort() {19         return port;20     }21 22     public void setPort(int port) {23         this.port = port;24     }25 }

    我們發現在這個類寫好後提示有錯誤

     

    在pom檔案加上依賴包,問題解決

    <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-configuration-processor</artifactId>    <optional>true</optional></dependency>

    建立一個自動設定類TestServiceAutoConfiguration

     1 package com.tanghuachun.teststarter; 2  3 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 4 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 5 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 6 import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 10 @Configuration11 @ConditionalOnClass(TestService.class)// 存在TestService這個類才裝配當前類12 @ConditionalOnProperty(name = "test-config.enabled", havingValue = "true", matchIfMissing = true)//設定檔存在這個test-config.enabled=true才啟動,允許不存在該配置13 @EnableConfigurationProperties(TestServiceProperties.class)14 public class TestServiceAutoConfiguration {15     @Bean16     @ConditionalOnMissingBean   // 沒有TestService這個類才進行裝配17     public TestService testService(TestServiceProperties testServiceProperties) {18         return new TestService(testServiceProperties.getHost(), testServiceProperties.getPort());19     }20 }

    相關註解含義在注釋中已經說明,到這裡,代碼已經寫好了,我們希望以註解的方式給使用者使用,自訂一個註解@EnableTestService

     1 package com.tanghuachun.teststarter; 2 import org.springframework.context.annotation.Import; 3 import java.lang.annotation.*; 4  5 @Inherited 6 @Documented 7 @Target(ElementType.TYPE) 8 @Retention(RetentionPolicy.RUNTIME) 9 @Import(TestServiceAutoConfiguration.class)10 //相當於使用定義spring.factories完成Bean的自動裝配11 public @interface EnableTestService {12 //@Import(TestServiceAutoConfiguration.class) 需要在調用者的Main 類加上該註解就能等效於spring.factories 檔案配置13 }

    然後注釋掉pom檔案中的maven外掛程式,如

    然後maven打包,就會產生一個jar包,這個jar包我們就可以直接用了

     這裡因為在本地環境測試,我們將編譯好的jar安裝到本地maven倉庫,點擊右邊的install按鈕(你也可以匯入編譯好的jar包一樣的)

  3. jar包使用

    我們開始來測試我們封裝好的jar,首先建立一個springboot項目(建立時一路預設,你的包名也可以和我一樣,無所謂的)

    pom檔案的依賴配置如下

    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>com.tanghuachun</groupId>            <artifactId>test-starter</artifactId>            <version>0.0.1-SNAPSHOT</version>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency></dependencies>

    在main入口類加上註解

    建立一個TestController類

     1 package com.tanghuachun.testmain; 2  3 import com.tanghuachun.teststarter.TestService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.web.bind.annotation.GetMapping; 6 import org.springframework.web.bind.annotation.RestController; 7  8 @RestController 9 public class TestController {10     @Autowired11     private TestService testService;12 13     @GetMapping(value = "/test")14     public String test(){15         testService.printConfInfo();16         return "OK";17     }18 }

    接下來在application.properties中配置參數

     

    啟動該項目,在地址欄輸入 http://localhost:8080/test 斷行符號,看控制台列印的資訊恰好是我們需要的

    到這裡我們就完成了一個自動設定的封裝。

    騷年們可以研究一下starter中註解@ConditionalOnProperty對使用的影響。

    今天的故事講完了。

 

spring boot自動設定實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.