SpringBoot配置文件占位符

一.随机数

实体类代码:

复制代码
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

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

相关推荐
wgslucky2 小时前
sm2 js加密,java服务器端解密
java·开发语言·javascript
韩立学长2 小时前
【开题答辩实录分享】以《在线预问诊系统设计与实现》为例进行选题答辩实录分享
vue.js·spring boot·mysql
running up that hill2 小时前
日常刷题记录
java·数据结构·算法
独自破碎E2 小时前
【快手手撕】合并区间
android·java
Loo国昌2 小时前
【LangChain1.0】第十四阶段:Agent最佳设计模式与生产实践
人工智能·后端·算法·语言模型·架构
seven97_top2 小时前
CopyOnWriteArrayList:写时复制机制与高效并发访问
java
不穿格子的程序员2 小时前
设计模式篇2——观察者模式:以直播间送礼系统举例
java·观察者模式·设计模式
萤丰信息2 小时前
四大核心技术领航,智慧园区重构产业生态新范式
java·大数据·人工智能·智慧城市·智慧园区
九号铅笔芯2 小时前
社区评论系统设计
java·数据库·sql