【问题标题】:Injection of null or an empty string as the default value of a property注入 null 或空字符串作为属性的默认值
【发布时间】:2012-11-28 19:51:26
【问题描述】:

如果没有指定属性,是否可以注入 null 或空白字符串作为将在 spring 文件中使用的默认值?目前我拥有的最好的是

<constructor-arg index="1" value="@{data.url:&quot;&quot;}"/>

在代码中解析为""

【问题讨论】:

  • 我认为 &lt;constructor-arg value=""/&gt; 应该可以工作。如果您需要索引,您可以添加它。也许我没有正确回答您的问题?
  • 将始终发送一个空字符串。只有在关联的属性文件中未指定空字符串时,我才对空字符串感兴趣。请看stackoverflow.com/a/2534949/222867

标签: spring


【解决方案1】:

您是否尝试过使用SpEL?可能是这样的:

<constructor-arg index="1" value="#{'${data.url}'==null?'':'${data.url}'}"/>

更新

我只记得有一种更简单的方法(正如 here 所描述的那样)。试试:

<constructor-arg index="1" value="${data.url:''}"/>

【讨论】:

  • 在 Spring 3.0.7 中,我制作了 "#{ '${data.url}' != 'null' ? '${data.url}' : '' }" 因为只是 != null没用
【解决方案2】:

如果您在源代码中使用注释,这将起到作用:

@Value("${data.url:#{null}}")
private String dataUrl;

【讨论】:

    【解决方案3】:

    Empty-Elvis 为我工作...

    @Value("${http.proxyHost?:}")
    public String proxyHost = null;
    

    【讨论】:

    • Eclipse Oxygen 在我执行此操作时会生成一个表达式预期警告。不过,它确实有效。我猜这是一个 Eclipse 问题。
    猜你喜欢
    • 1970-01-01
    • 2016-12-11
    • 2018-02-17
    • 2014-02-09
    • 2011-07-06
    • 2017-10-06
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多