[Spring Boot] (5), random numbers and placeholders for configuration files

The Spring Boot global configuration file supports adding properties using random numbers and placeholders.

1. Random numbers

  • ${random.value}

  • ${random.int}

  • ${random.int(max)}

  • ${random.int(min,max)}

  • ${random.long}

  • ${random.long(max)}

  • ${random.long(min,max)}

  • ${random.uuid}

Random numbers are parsed using the RandomValuePropertySource class. Note: When using IDEA for random number configuration, the second and third random numbers of long will not be prompted. The blogger also found out when looking at 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")) {//${random.int}
            //getSource() returns the actual object of the generic T, so nextInt() is to call the nextInt() method of the Random class
			return getSource().nextInt();
		}
		if (type.equals("long")) {//${random.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")) {//${random.uuid}
			return UUID.randomUUID().toString();
		}
		return getRandomBytes();//${random.value}
	}

	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) {//${random.int(value)}
			return getSource().nextInt(start);
		}
        //${random.int(value,max)}
		return start + getSource().nextInt(Integer.parseInt(tokens[1]) - start);
	}

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

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

	//...
}

        Bloggers have a habit that if there are variables after the punctuation mark, they like to type an extra space after the punctuation mark to facilitate viewing and keep the layout clean. When using $ {random.int(min,max)}, I like to type ${random.int(min, max)}. Note that there is a space between the comma and max. When the blogger wrote a variable $ {random.long(20000, 99999)}, when debugging, it was found that an error was always reported during parsing. Later, when looking at the exception, it was found that "99999" could not be parsed. The original comma and You can't write spaces between max, what a pit! ! !

Note: For random with two values ​​of min and max written, there must be no spaces between min and max, only commas, otherwise it will not be parsed when the source code is parsed, and an exception will be reported. For example: ${random.int(100,200)} is correct, but $ {random.int(100, 200)} is wrong, please pay attention to prevent getting into the pit! ! !


   

2. Placeholder

The previous property value can be referenced, or the default value can be used if there is none. For example: $ {aaa:default}, if ${aaa} does not exist, use default instead of the value of aaa; if $ {aaa} exists, use the value of $ {aaa}.


a = ${random.int}
b = ${random.int(100)}
c = ${random.int(500,1000)}
d = ${random.long}
e = ${random.long(10000)}
f = ${random.long(20000,99999)}
g = ${random.value}
h = ${random.uuid}
i = ${aaa:"bbb"}

When parsing placeholders, such as a variable , when referencing the i variable, the value of i will be parsed first, then the value of $ {aaa:"bbb"} will be parsed, and then the value of $ {aaa} will be parsed , if it exists, use the value of the aaa variable directly, if it does not exist, use "bbb" directly as the value of the a variable, which is actually a recursive analysis .i = ${aaa:"bbb"}




=====================Make an advertisement, welcome to pay attention =====================

QQ:
412425870
WeChat public account: Cay Classroom

csdn blog:
http://blog.csdn.net/caychen
Code cloud:
https://gitee.com/caychen/
github:
https://github.com/caychen

Click on the group number or scan the QR code to join the QQ group:

328243383 (1 group)




Click on the group number or scan the QR code to join the QQ group:

180479701 (2 groups)




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325709838&siteId=291194637