You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot无法打印系统属性,寻求两种获取monthly.text的实现方式

问题分析与解决方案

1. 确保系统属性正确传递

首先要保证monthly.text系统属性已正确传入应用:

  • 命令行启动时添加JVM参数:java -jar your-app.jar -Dmonthly.text="你要设置的内容"
  • IDE运行配置中添加VM选项:-Dmonthly.text="测试文本"

2. @Value两种语法的正确实现

方式一:${}直接读取系统属性

在FooController中注入属性,可添加默认值避免属性不存在时抛出异常:

@RestController
public class FooController {

    @Value("${monthly.text:默认文本}")
    private String monthlyTextDollar;

    @GetMapping("/test-dollar")
    public String printDollarStyle() {
        return "通过${}获取的系统属性:" + monthlyTextDollar;
    }
}

方式二:#{}通过SpEL表达式读取系统属性

SpEL需通过systemProperties对象访问系统属性,同样支持默认值:

@RestController
public class FooController {

    @Value("#{systemProperties['monthly.text'] ?: '默认文本'}")
    private String monthlyTextHash;

    @GetMapping("/test-hash")
    public String printHashStyle() {
        return "通过#{}获取的系统属性:" + monthlyTextHash;
    }
}

3. 验证Undertow依赖配置

确保pom.xml中已正确替换Web服务器为Undertow:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
</dependencies>

4. 测试与排查

启动应用后,分别访问/test-dollar和/test-hash接口查看结果。若仍无法获取,检查:

  • 系统属性名称拼写是否完全一致(大小写敏感)
  • 应用启动时是否确实传递了该属性
  • FooController是否在Spring Boot主启动类的扫描包范围内

内容的提问来源于stack exchange,提问作者Đỗ Như Vỹ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:23:15