1. 程式人生 > >Spring Boot 學習筆記 2 : Random

Spring Boot 學習筆記 2 : Random

官方文件介紹

The RandomValuePropertySource is useful for injecting random values (e.g. into secrets or test cases). It can produce integers, longs, uuids or strings, e.g.

RandomValuePropertySource 類通常用來注入 int,long,uuid 和 string 型別的隨機值。

The random.int* syntax is OPEN value (,max) CLOSE where the OPEN,CLOSE are any character and value,max are integers. If max is provided then value is the minimum value and max is the maximum (exclusive).

random.int* 的語法是 OPEN value (,max) CLOSE 。OPEN 和 CLOSE 可以是 任意字元,用來分隔方法引數。value, max 是 int 型別的整數。如果 max 引數存在,則 value 表示取值範圍的最小值,max 表示最大值(不包含 max)。

編寫配置檔案

application.properties 檔案配置:

my.value=${random.value}
my.int=${random.int}
my.long=${random.long}
my.uuid=${random.uuid}
my.int.less.than.ten
=${random.int(10)} my.int.in.range=${random.int[1024,65536]}

application.yml 檔案配置:

my:
    value: ${random.value}
    int: ${random.int}
    long: ${random.long}
    uuid: ${random.uuid}
    int.less.than.ten: ${random.int(10)}
    # 100前面和1000後面可以是 -,(,[ 等任意字元
    int.in.range: ${random.int-100,1000-}

編寫 Controller 類

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/random")
public class RandomController {
    private static Logger log = LoggerFactory.getLogger(RandomController.class);

    //如果沒有編寫配置檔案,此處可以直接使用${random.value}
    @Value("${my.value}")
    private String randomValue;

    //如果沒有編寫配置檔案,此處可以直接使用${random.int}
    //int 型別也可以換成 String 型別
    @Value("${my.int}")
    private int randomInt;

    //如果沒有編寫配置檔案,此處可以直接使用${random.int(10)}
    //int 型別也可以換成 String 型別
    @Value("${my.int.less.than.ten}")
    private int randomIntLessThanTen;

    //如果沒有編寫配置檔案,此處可以直接使用${random.int[100,1000]}
    //int 型別也可以換成 String 型別
    @Value("${my.int.in.range}")
    private int randomIntRange;

    //如果沒有編寫配置檔案,此處可以直接使用${random.long}
    //long 型別也可以換成 String 型別
    @Value("${my.long}")
    private long randomLong;

    //如果沒有編寫配置檔案,此處可以直接使用${random.uuid}
    @Value("${my.uuid}")
    private String randomUUID;

    @RequestMapping("/value")
    public String getValue() {
        log.info("收到請求,randomValue : " + randomValue);
        return "randomValue : " + randomValue;
    }

    @RequestMapping("/int")
    public String getRandomInt() {
        log.info("收到請求,randomInt : " + randomInt);
        return "randomInt : " + randomInt;
    }

    @RequestMapping("/int/ten")
    public String getRandomIntLessThanTen() {
        log.info("收到請求,randomIntLessThanTen : " + randomIntLessThanTen);
        return "randomIntLessThanTen : " + randomIntLessThanTen;
    }

    @RequestMapping("/int/range")
    public String getRandomIntRange() {
        log.info("收到請求,randomIntRange : " + randomIntRange);
        return "randomIntRange : " + randomIntRange;
    }

    @RequestMapping("/long")
    public String getRandomLong() {
        log.info("收到請求,randomLong : " + randomLong);
        return "randomLong : " + randomLong;
    }

    @RequestMapping("/uuid")
    public String getRandomUUID() {
        log.info("收到請求,randomUUID : " + randomUUID);
        return "randomUUID : " + randomUUID;
    }
}

使用瀏覽器或 Postman 測試

randomUUID

random

注意事項及異常

  1. 使用 @Value 註解注入的變數不能使用 static 修飾符修飾,否則變數的值無法注入成功。

    static

  2. 編寫配置檔案時,鍵名不能以 “random” 開頭,否則會丟擲NumberFormatException 。

    NumberFormatException

    random:
        value: ${random.value}
        int: ${random.int}
        long: ${random.long}
        uuid: ${random.uuid}
        int.less.than.ten: ${random.int(10)}
        int.in.range: ${random.int-100,1000-}

    random.int.less.than.ten

    原因是 RandomValuePropertySource 在解析 ${random.int.less.than.ten} 和 ${random.int.in.range} 表示式時:

    1.會先呼叫 getProperty(String name) 方法擷取字首”random.” 後面的字串,得到”int.less.than.ten”和”int.in.range”

    2.然後會呼叫 getRandomValue(String type) 方法對剩下的字串進行匹配,發現是以 “int” 作為字首後

    3.會呼叫 getRange(String type, String prefix) 方法,擷取字首”int.”後面到 length - 1 位置的字串,得到”less.than.te”和”in.rang”

    4.最後會呼叫 getNextIntInRange(String range) 方法,將剩下的字串使用逗號分隔符切割後將返回陣列的首個物件轉換成 int 型別的數值作為 Random.nextInt(int bound) 方法的引數。

RandomValuePropertySource 類原始碼:

public class RandomValuePropertySource extends PropertySource<Random> {

    /**
     * Name of the random {@link PropertySource}.
     */
    public static final String RANDOM_PROPERTY_SOURCE_NAME = "random";

    private static final String PREFIX = "random.";

    private static final Log logger = LogFactory.getLog(RandomValuePropertySource.class);

    public RandomValuePropertySource(String name) {
        super(name, new Random());
    }

    public RandomValuePropertySource() {
        this(RANDOM_PROPERTY_SOURCE_NAME);
    }

    @Override
    public Object getProperty(String name) {
        if (!name.startsWith(PREFIX)) {
            return null;
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Generating random property for '" + name + "'");
        }
        return getRandomValue(name.substring(PREFIX.length()));
    }

    private Object getRandomValue(String type) {
        if (type.equals("int")) {
            return getSource().nextInt();
        }
        if (type.equals("long")) {
            return getSource().nextLong();
        }
        String range = getRange(type, "int");
        if (range != null) {
            return getNextIntInRange(range);
        }
        range = getRange(type, "long");
        if (range != null) {
            return getNextLongInRange(range);
        }
        if (type.equals("uuid")) {
            return UUID.randomUUID().toString();
        }
        return getRandomBytes();
    }

    private String getRange(String type, String prefix) {
        if (type.startsWith(prefix)) {
            int startIndex = prefix.length() + 1;
            if (type.length() > startIndex) {
                return type.substring(startIndex, type.length() - 1);
            }
        }
        return null;
    }

    private int getNextIntInRange(String range) {
        String[] tokens = StringUtils.commaDelimitedListToStringArray(range);
        int start = Integer.parseInt(tokens[0]);
        if (tokens.length == 1) {
            return getSource().nextInt(start);
        }
        return start + getSource().nextInt(Integer.parseInt(tokens[1]) - start);
    }

    private long getNextLongInRange(String range) {
        String[] tokens = StringUtils.commaDelimitedListToStringArray(range);
        if (tokens.length == 1) {
            return Math.abs(getSource().nextLong() % Long.parseLong(tokens[0]));
        }
        long lowerBound = Long.parseLong(tokens[0]);
        long upperBound = Long.parseLong(tokens[1]) - lowerBound;
        return lowerBound + Math.abs(getSource().nextLong() % upperBound);
    }

    private Object getRandomBytes() {
        byte[] bytes = new byte[32];
        getSource().nextBytes(bytes);
        return DigestUtils.md5DigestAsHex(bytes);
    }

    public static void addToEnvironment(ConfigurableEnvironment environment) {
        environment.getPropertySources().addAfter(
                StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
                new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME));
        logger.trace("RandomValuePropertySource add to Environment");
    }

}

相關推薦

Spring Boot 學習筆記 2 : Random

官方文件介紹 The RandomValuePropertySource is useful for injecting random values (e.g. into secrets or test cases). It can produce integ

Spring boot學習筆記2--pom.xml初探究

新建的springboot_study專案的pom.xml結構如下: <parent> <groupId>org.springframework.boot</groupId> <artifactId&g

Spring Boot學習筆記2——基本使用之最佳實踐[z]

前言 在上一篇文章Spring Boot 學習筆記1——初體驗之3分鐘啟動你的Web應用已經對Spring Boot的基本體系與基本使用進行了學習,本文主要目的是更加進一步的來說明對於Spring Boot使用上的具體的細節以及使用上的最佳實踐, 經過了幾天的文件閱讀和實驗,將自己這幾天的學習心得在

Spring Boot學習筆記2

Spring Boot屬性配置檔案詳解 自定義屬性與載入 我們在使用Spring Boot的時候,通常也需要定義一些自己使用的屬性,我們可以如下方式直接定義: com.didispace.blog.name=程式猿DD com.didispace.blog.

spring boot 學習筆記2Spring Boot 依賴環境和專案結構介紹

使用 Spring Boot 開發專案需要有兩個基礎環境和一個開發工具,這兩個環境是指 Java 編譯環境和構建工具環境,一個開發工具是指 IDE 開發工具。 Spring Boot 2.0 要求 Java 8 作為最低版本,需要在本機安裝 JDK 1.8 並進行環境變數配置,同時需要安裝構建工

2小時學會Spring Boot 學習筆記

前言 Spring Boot是用來簡化Spring應用初始搭建以及開發過程的全新框架,被認為是SpringMVC的接班人,和微服務緊密聯絡在一起。Spring Boot 簡單例項Demo SpringMVC 的優缺點 優點: Spring Boot

我的第一個spring boot程序(spring boot 學習筆記之二)

獲取json 了解 訪問 static 依賴 過程 public 獲取數據 gap 第一個spring boot程序 寫在前面:鑒於spring註解以及springMVC的配置有大量細節和知識點,在學習理解之後,我們將直接進入spring boot的學習,在後續學習中用到註

Spring Boot學習筆記

end 應用程序 maven構建 筆記 項目依賴 新建 輸入 需要 文本 1.不需要任何特殊工具集成,可以使用任何IDE或文本編輯器。 2.Spring Boot CLI是一個命令行工具。 3.使用Maven構建一個基於Spring Boot 的Web應用程序。   1)打

Spring Boot 學習筆記(二)

imp family framework ima pri spa cal bin ges 新建Srping Boot 項目 以下是項目結構 由於Srping Boot內置Tomcat,所以不需要配置Tomcat就可以直接運行。 HelloWorldAppli

Java框架spring Boot學習筆記(八):Spring相關概念

擴展 靜態 輕量級 想要 spring配置 核心 使用 oot 調用方法 Spring是開源、輕量級、一站式框架。 Spring核心主要兩部分 aop:面向切面編程,擴展功能不是修改源代碼實現 ioc:控制反轉,比如一個類,在類裏面有方法(不是靜態的方法),想要調用類

Java框架spring Boot學習筆記(十四):log4j介紹

inf alt 技術分享 images 使用 image 詳細 配置文件 -128 功能 日誌功能,通過log4j可以看到程序運行過程的詳細信息。 使用 導入log4j的jar包 復制log4j的配置文件,復制到src下面         3.設置日誌級別    

Spring Boot學習筆記-配置devtools實現熱部署

原理 enc cnblogs 配置文件 target res 快的 pen cache 寫在前面   Spring為開發者提供了一個名為spring-boot-devtools的模塊來使Spring Boot應用支持熱部署,提高開發者的開發效率,無需手動重啟Spring

1、spring-boot學習筆記(一)簡單入門

ava project nal run plugin mailto 5.4 安全 class a 一、新建普通Maven工程 pom.xml <parent> <groupId>org.springframework.boot</gr

Spring Boot學習筆記之一:傳統maven項目與采用spring boot項目區別

bubuko xml文件 分享 lda ring info 插件 eclips web 項目結構區別 傳統的maven構建的項目結構如下: 用maven構建的采用springboot項目結構如下: 二者結構一致,區別如下:傳統項目如果需要打成war包,需要在WEB-IN

Spring Boot學習筆記——Spring Boot與Redis的集成

pac urn prope web property static 接口 per select 一.添加Redis緩存 1.添加Redis起步依賴 在pom.xml中添加Spring Boot支持Redis的依賴配置,具體如下: <dependency>

Spring Boot學習筆記:JavaMailSender發送郵件

獲取 prop create subject intern dex autowired 需求 see 項目中經常會有這樣的需求,用戶註冊成功,需要給用戶發送一封郵件。郵件需要有一定格式和樣式。本次例子中用freemarker做樣式,其他的模版引擎類似。 首先Spring B

Spring boot 學習筆記 1 - 自定義錯誤

note ride 覆蓋 ide rac med exception cat 異常 Spring Boot提供了WebExceptionHandler一個以合理的方式處理所有錯誤的方法。它在處理順序中的位置就在WebFlux提供的處理程序之前,這被認為是最後一個處理程序。

Spring Boot學習筆記之使用Spring Boot建立一個簡單的web專案(工具使用IntelliJ IDEA)

新建Maven專案 1.File --> New Project --> Maven --> Next 2.填寫專案資訊,完成之後點選Next,然後點選Finish 3.專案建好之後如下圖所示 修改pom檔案中的配置資訊 <?xml version

Spring Boot學習筆記之使用Spring Boots實現資料庫操作(IntelliJ IDEA+navicat for Sql Server)

這裡使用Spring Boot實現了一個簡單的專案,能夠實現簡單的資料庫操作,工具使用的是IntelliJ IDEA2017.3,資料庫工具使用的是navicat for Sql Server,語言使用的Java。 1.新建一個空的Maven專案 2.匯入需要的jar包 pom.xml: