SpEL函数更改字符串

huangapple go评论75阅读模式
英文:

SpEL function changes String

问题

myProperties.properties
myValue={ "myWorkingKey": "Hi!", "myNonWorkingKey": "" }


MyClass.java
public class MyClass {

  @Value("#{ '${myValue}' }")
  public void printWithSpEL(String withSpEL){
    System.out.println(withSpEL);
  }

  @Value("${myValue}")
  public void printWithOut(String without){
    System.out.println(without);
  }
}

result after startup:

{ "myWorkingKey": "Hi!", "myNonWorkingKey": "" }
{ "myWorkingKey": "Hi!", "myNonWorkingKey": "" }
英文:

I am trying to take a String from properties, run an operation on it, then store it as a variable with the @Value annotation. Unfortunately, when I use the #{'${variable}'} syntax that I need to use to use SpEL, the String changes. If I have two double quotes (""), they are changed to a single double quote (") which prevents me from deserializing the String. How do I prevent Spring from removing that 2nd quotation mark?

myProperties.properties
myValue={"myWorkingKey": "Hi!", "myNonWorkingKey": ""}


MyClass.java
public class MyClass {

  @Value("#{'${myValue}'}")
  public void printWithSpEL(String withSpEL){
    System.out.println(withSpEL);
  }

  @Value("${myValue}")
  public void printWithOut(String without){
    System.out.println(without);
  }
}

result after startup:

{"myWorkingKey": "Hi!", "myNonWorkingKey": "}
{"myWorkingKey": "Hi!", "myNonWorkingKey": ""}


</details>


# 答案1
**得分**: 1

为什么需要在这样一个简单的值上使用 SpEL?属性占位符已经足够了。

或者这只是一个基于更复杂内容的示例。

使用 SpEL 需要三重引号:

    myValue={&quot;myWorkingKey&quot;: &quot;Hi!&quot;, &quot;myNonWorkingKey&quot;: &quot;&quot;&quot;}

<details>
<summary>英文:</summary>

Why do you need to use SpEL for such a simple value? The property placeholder is enough.

Or is this just an example based on something more complex.

With SpEL you need triple quotes:

    myValue={&quot;myWorkingKey&quot;: &quot;Hi!&quot;, &quot;myNonWorkingKey&quot;: &quot;&quot;&quot;}


</details>



# 答案2
**得分**: 0

为什么要加载到 `String` 中?改为加载到 `Map&lt;String, String&gt;` 中。

```java
@Value(&quot;#{${myValue}}&quot;)
public void printWithSpEL(Map&lt;String, String&gt; withSpEL){
    System.out.println(withSpEL);
}
英文:

Why you want to load it into String? Load instead into Map&lt;String, String&gt;.

@Value(&quot;#{${myValue}}&quot;)
public void printWithSpEL(Map&lt;String, String&gt; withSpEL){
    System.out.println(withSpEL);
}

huangapple
  • 本文由 发表于 2020年3月4日 04:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/60514858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定