溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何開發(fā)Spring Boot Starter

發(fā)布時間:2021-11-24 09:37:18 來源:億速云 閱讀:156 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“如何開發(fā)Spring Boot Starter”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“如何開發(fā)Spring Boot Starter”這篇文章吧。

關(guān)于Starter

Spring Boot秉承“約定大于配置”的開發(fā)方式,使得我們基于Spring Boot開發(fā)項目的效率變得十分高。相信使用過Spring Boot的小伙伴都會發(fā)現(xiàn),當我們要用到某個Spring提供的組件時,只需要在pom.xml文件中添加該組件的starter依賴就能集成到項目中。

例如,在pom.xml文件中添加spring-boot-starter-web依賴,就能讓項目整合Spring MVC的功能。并且在最簡使用下幾乎不需要進行任何的配置,而以往想要集成Spring MVC,不僅要添加一堆類似于spring-web、spring-webmvc等相關(guān)依賴包,以及完成許多繁雜的配置才能夠?qū)崿F(xiàn)集成。

這是因為starter里已經(jīng)幫我們整合了各種依賴包,避免了依賴包缺失或依賴包之間出現(xiàn)版本沖突等問題。以及完成了許多基礎(chǔ)配置和自動裝配,讓我們可以在最簡使用下,跳過絕大部分的配置,從而達到開箱即用的效果。這也是Spring Boot實現(xiàn)“約定大于配置”的核心之一。


動手開發(fā)一個Starter

通過以上的描述,我們可以簡單地將starter看作是對一個組件功能粒度較大的模塊化封裝,包括了所需依賴包的整合及基礎(chǔ)配置和自動裝配等。

除了Spring官方提供的starter外,我們自己也可以根據(jù)業(yè)務(wù)開發(fā)一個starter。例如,當項目積累到一定程度時,我們可以將一些通用功能下沉為一個starter。而開發(fā)一個starter也很簡單,只需要以下步驟:

  1. 新建一個Maven項目,在pom.xml文件中定義好所需依賴;

  2. 新建配置類,寫好配置項和默認值,使用@ConfigurationProperties指明配置項前綴;

  3. 新建自動裝配類,使用@Configuration@Bean來進行自動裝配;

  4. 新建spring.factories文件,用于指定自動裝配類的路徑;

  5. 將starter安裝到maven倉庫,讓其他項目能夠引用;

接下來,以封裝一個用于操作redis的starter為例,一步步展示這些步驟的具體實現(xiàn)過程。首先是第一步,新建一個maven項目,完整的pom.xml內(nèi)容如下:

<?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 https://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.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-boot-starter-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-starter-demo</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</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
    </dependencies>
</project>

第二步,新建一個屬性配置類,寫好配置項和默認值。并使用@ConfigurationProperties指明配置項前綴,用于加載配置文件對應(yīng)的前綴配置項:

package com.example.starter.demo.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 屬性配置類,用于加載配置文件對應(yīng)的前綴配置項
 *
 * @author zero
 * @date 2019-11-04
 **/
@Data
@ConfigurationProperties("demo.redis")
public class RedisProperties {

    private String host = "127.0.0.1";

    private int port = 6379;

    private int timeout = 2000;

    private int maxIdle = 5;

    private int maxTotal = 10;

    private long maxWaitMillis = 10000;

    private String password;
}

編寫一個簡單的redis操作工具,代碼如下:

package com.example.starter.demo.component;

import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * redis 操作組件
 *
 * @author zero
 * @date 2019-11-04
 **/
@Slf4j
@RequiredArgsConstructor
public class RedisComponent {

    private final JedisPool jedisPool;

    /**
     * get value with key
     */
    public <T> T get(String key, Class<T> clazz) {
        try (Jedis resource = jedisPool.getResource()) {
            String str = resource.get(key);

            return stringToBean(str, clazz);
        }
    }

    /**
     * set value with key
     */
    public <T> boolean set(String key, T value, int expireSeconds) {
        try (Jedis resource = jedisPool.getResource()) {
            String valueStr = beanToString(value);
            if (valueStr == null || valueStr.length() == 0) {
                return false;
            }

            if (expireSeconds <= 0) {
                resource.set(key, valueStr);
            } else {
                resource.setex(key, expireSeconds, valueStr);
            }

            return true;
        }
    }

    private <T> T stringToBean(String str, Class<T> clazz) {
        Gson gson = new Gson();
        return gson.fromJson(str, clazz);
    }

    private <T> String beanToString(T value) {
        Gson gson = new Gson();
        return gson.toJson(value);
    }
}

第三步,新建自動裝配類,使用@Configuration@Bean來實現(xiàn)對JedisPoolRedisComponent的自動裝配;

package com.example.starter.demo.configuration;

import com.example.starter.demo.component.RedisComponent;
import com.example.starter.demo.properties.RedisProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 自動裝配類
 *
 * @author zero
 * @date 2019-11-04
 **/
@Slf4j
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfiguration {

    private final RedisProperties properties;

    @Bean
    // 表示當Spring容器中沒有JedisPool類的對象時,才調(diào)用該方法
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool jedisPool() {
        log.info("redis connect string: {}:{}", properties.getHost(), properties.getPort());
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(properties.getMaxIdle());
        jedisPoolConfig.setMaxTotal(properties.getMaxTotal());
        jedisPoolConfig.setMaxWaitMillis(properties.getMaxWaitMillis());

        String password = properties.getPassword();
        if (password == null || password.length() == 0) {
            return new JedisPool(jedisPoolConfig, properties.getHost(),
                    properties.getPort(), properties.getTimeout());
        }

        return new JedisPool(jedisPoolConfig, properties.getHost(),
                properties.getPort(), properties.getTimeout(), properties.getPassword());
    }

    @Bean
    @ConditionalOnMissingBean(RedisComponent.class)
    public RedisComponent redisComponent(JedisPool jedisPool){
        return new RedisComponent(jedisPool);
    }
}

第四步,在項目的resources目錄下新建一個META-INF目錄,并在該目錄下新建spring.factories文件。如下圖所示:
如何開發(fā)Spring Boot Starter

spring.factories文件里指定自動裝配類的路徑:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.starter.demo.configuration.RedisConfiguration

若需要指定多個自動裝配類的路徑,則使用逗號分隔。如下示例:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.starter.demo.configuration.DemoConfiguration,\
  com.example.starter.demo.configuration.RedisConfiguration

Tips:spring.factories支持配置的key如下:

org.springframework.context.ApplicationContextInitializer
org.springframework.context.ApplicationListener
org.springframework.boot.autoconfigure.AutoConfigurationImportListener
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter
org.springframework.boot.autoconfigure.EnableAutoConfiguration
org.springframework.boot.diagnostics.FailureAnalyzer
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider
org.springframework.boot.env.EnvironmentPostProcessor
org.springframework.boot.SpringApplicationRunListener
org.springframework.boot.SpringBootExceptionReporter
org.springframework.beans.BeanInfoFactory
org.springframework.boot.env.PropertySourceLoader
org.springframework.data.web.config.SpringDataJacksonModules
org.springframework.data.repository.core.support.RepositoryFactorySupport

最后install這個maven項目,命令如下:

mvn clean install

如果使用的開發(fā)工具是IDEA的話就比較簡單,只需要雙擊一下install即可:
如何開發(fā)Spring Boot Starter


使用Starter

在任意一個Spring Boot項目的pom.xml文件中添加如下依賴:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>spring-boot-starter-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
 </dependency>

在項目的application.yml中添加如下配置項來覆蓋默認配置,若默認配置已符合需求則可以省略這一步:

demo:
  redis:
    host: 192.168.11.130
    port: 6379
    timeout: 3000
    password: A8^MZ59qOr*gkhv51tSdifvb
    max-total: 10
    max-wait-millis: 10000
    max-idle: 10

編寫一個單元測試類進行測試,代碼如下:

package com.example.firstproject.starter;

import com.example.starter.demo.component.RedisComponent;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class StarterTests {

    @Autowired
    private RedisComponent redisComponent;

    @Test
    public void redisTest() {
        String key = "redisTest";
        String value = "this is a test value";
        boolean success = redisComponent.set(key, value, 3600);
        log.info("set value to redis {}!", success ? "success" : "failed");
        String result = redisComponent.get(key, String.class);
        log.info("get value from redis: [{}]", result);
    }
}

運行結(jié)果如下:
如何開發(fā)Spring Boot Starter

以上是“如何開發(fā)Spring Boot Starter”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI