SpEL函数更改字符串

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

SpEL function changes String

问题

  1. myProperties.properties
  2. myValue={ "myWorkingKey": "Hi!", "myNonWorkingKey": "" }
  3. MyClass.java
  4. public class MyClass {
  5. @Value("#{ '${myValue}' }")
  6. public void printWithSpEL(String withSpEL){
  7. System.out.println(withSpEL);
  8. }
  9. @Value("${myValue}")
  10. public void printWithOut(String without){
  11. System.out.println(without);
  12. }
  13. }

result after startup:

  1. { "myWorkingKey": "Hi!", "myNonWorkingKey": "" }
  2. { "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?

  1. myProperties.properties
  2. myValue={"myWorkingKey": "Hi!", "myNonWorkingKey": ""}
  3. MyClass.java
  4. public class MyClass {
  5. @Value("#{'${myValue}'}")
  6. public void printWithSpEL(String withSpEL){
  7. System.out.println(withSpEL);
  8. }
  9. @Value("${myValue}")
  10. public void printWithOut(String without){
  11. System.out.println(without);
  12. }
  13. }

result after startup:

  1. {"myWorkingKey": "Hi!", "myNonWorkingKey": "}
  2. {"myWorkingKey": "Hi!", "myNonWorkingKey": ""}
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 为什么需要在这样一个简单的值上使用 SpEL?属性占位符已经足够了。
  7. 或者这只是一个基于更复杂内容的示例。
  8. 使用 SpEL 需要三重引号:
  9. myValue={&quot;myWorkingKey&quot;: &quot;Hi!&quot;, &quot;myNonWorkingKey&quot;: &quot;&quot;&quot;}
  10. <details>
  11. <summary>英文:</summary>
  12. Why do you need to use SpEL for such a simple value? The property placeholder is enough.
  13. Or is this just an example based on something more complex.
  14. With SpEL you need triple quotes:
  15. myValue={&quot;myWorkingKey&quot;: &quot;Hi!&quot;, &quot;myNonWorkingKey&quot;: &quot;&quot;&quot;}
  16. </details>
  17. # 答案2
  18. **得分**: 0
  19. 为什么要加载到 `String` 中?改为加载到 `Map&lt;String, String&gt;` 中。
  20. ```java
  21. @Value(&quot;#{${myValue}}&quot;)
  22. public void printWithSpEL(Map&lt;String, String&gt; withSpEL){
  23. System.out.println(withSpEL);
  24. }
英文:

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

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

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:

确定