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

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

相关推荐
豆瓣鸡10 分钟前
封装 API 请求日志切面——从注解定义到 Starter 自动装配
java·开发语言·spring boot
高明珠18 分钟前
麒麟 V10 SP1 踩坑:`./startup.sh` 报“解释器错误: 权限不够“,根因是 KySec
后端
用户83580861879130 分钟前
基于Redis的分布式锁优化实践:从Redlock到自适应自旋的实现与思考
后端
掘金者阿豪36 分钟前
想让短视频自动生产?用MoneyPrinterTurbo搭一个远程可控的AI创作平台
后端
掉鱼的猫1 小时前
把 OpenAPI 接入 Agent Harness:零代码让 Agent 听懂你的 REST API
java·llm·agent
梨子同志1 小时前
开发工具
前端·后端
梨子同志1 小时前
Java
后端
lzhcoder1 小时前
Spring Boot 集成 Kafka:先跑通 Demo,再避开那 80% 的人踩过的坑
java·kafka
像我这样帅的人丶你还1 小时前
Java 后端详解(六):Maven 与本地开发指南
前端·后端
tonydf1 小时前
.NET 项目集成可观测性:从架构思考到落地实践
运维·后端