一.随机数
实体类代码:
package com.qcby.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "random")
public class RandomConfig {
private String value;
private int intValue;
private long longValue;
private int intInRange;
private int intWithLimit;
// Getters 和 Setters
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public long getLongValue() {
return longValue;
}
public void setLongValue(long longValue) {
this.longValue = longValue;
}
public int getIntInRange() {
return intInRange;
}
public void setIntInRange(int intInRange) {
this.intInRange = intInRange;
}
public int getIntWithLimit() {
return intWithLimit;
}
public void setIntWithLimit(int intWithLimit) {
this.intWithLimit = intWithLimit;
}
@Override
public String toString() {
return "RandomConfig{" +
"value='" + value + '\'' +
", intValue=" + intValue +
", longValue=" + longValue +
", intInRange=" + intInRange +
", intWithLimit=" + intWithLimit +
'}';
}
}
yml里面加
random:
value: ${random.value} # 随机的 UUID 值
intvalue: ${random.int} # 随机的整数
longvalue: ${random.long} # 随机的长整型数值
intInRange: ${random.int[1024,65536]} # 随机的整数,范围从 1024 到 65536
intWithLimit: ${random.int(10)} # 随机生成一个 0 到 10 之间的整数
启动类
@SpringBootApplication
@EnableConfigurationProperties(person.class)
@ImportResource("classpath:beans.xml")//导入xml注解
public class mavenSpringBootDemo {
@Autowired
private RandomConfig randomConfig;
public static void main(String[] args) {
SpringApplication.run(mavenSpringBootDemo.class,args);
}
@Bean
public CommandLineRunner run() {
return args -> {
// 打印随机配置的值
System.out.println("Random Config: " + randomConfig);
};
}
}
控制台打印

二.占位符获取之前配置的值,如果没有可以是用:指定默认值
yml里改
age: ${random.int:70}
启动上面的配置类
打印的值随机生成为了4

注意:如果年龄字段有数据校验,要注释掉