【问题标题】:How to pass empty string as a command line property to Spring?如何将空字符串作为命令行属性传递给 Spring?
【发布时间】:2018-08-16 05:53:18
【问题描述】:

仅供参考:我正在使用 Intellij 的“运行/调试配置”工具。

我想通过命令行将一个空字符串作为属性传递给我的应用程序:

--spring.ldap.username=

我试过了:

--spring.ldap.username= # results in parse error
--spring.ldap.username=''
--spring.ldap.username="" # results in parse error
--spring.ldap.username=\"\"

实际成功解析的尝试产生了不正确的值,正如我尝试打印“空”字符串时所展示的那样:

System.out.println(environment.getProperty("spring.ldap.username"));

// returns:
// ''
// ""

在 application.properties 文件中将相同的属性设置为空字符串效果很好:

spring.ldap.username=

同样的打印语句:

// returns:
//
// ^^ totally empty string

我错过了什么技巧吗?

【问题讨论】:

  • 您可以在应用程序的运行/调试配置中通过Environment variables 输入它们吗?
  • 这可能行得通,但我想通过命令行传递这些参数。
  • 您可能想多了 - 只是将该参数的值默认为代码中的空字符串就足够了吗?是否需要将空字符串作为参数提取?
  • 我认为如果将一个空字符串(在这种情况下是一个合理的值)传递给标志不会破坏事情,它会简化我系统中其他地方的代码。话虽如此,我现在可能会接受你的建议。

标签: spring intellij-idea properties command-line-arguments


【解决方案1】:

事实证明,这可以通过使用常规 JVM 参数来完成。

代替

--my.property=

使用

-Dmy.property=

我猜本机 JVM 参数能够接受空字符串。

在 IntelliJ 中,您可以将它们添加到 Run/Debug Configurations 窗口的相应字段中,如下所示:

This answer 到另一个问题也有一些关于将 JVM 参数传递给 Spring 应用程序的更多信息。

【讨论】:

    【解决方案2】:

    试试这个:--spring.ldap.username(如果你离开=,它将被解析为空)

    【讨论】:

    • 我看错了你的回答;这也有效。我不知道为什么我从来没想过要尝试这个。
    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多