2011-04-13 193 views
27

我有一个常用的自动装载属性值的groovy类。使用@Value使用Groovy进行Spring注释

如:

public @Value("${valueA}") String valueA; 

在我机应用方面加入了性能占位符的

<context:property-placeholder location="classpath:spring/app.properties" /> 

的app.properties是否有“值a”设置,因此在理论上这应该值在运行时在我的类中填充字符串valueA。

如果我使用java类,但是如果我使用groovy类,则此设置完美工作。

我得到一个编译错误:

Error: expected '$valueA' to be an inline constant of type java.lang.String in @org.springframework.beans.factory.annotation.Value
Error: Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' in @org.springframework.beans.factory.annotation.Value

我只是想知道,如果以上语法使用Groovy类时是正确的,如果没有什么是在运行时自动装配的@Value参数的正确语法。

+0

感谢您提出这个问题。这让我有点疯狂,但下面的答案可以做到。 – 2014-06-08 18:08:31

回答

47

使用单引号,即。

public @Value('${valueA}') String valueA 
+0

这是因为用双引号你得到一个GString而不是一个字符串,并且替换是在错误的时间完成的? – 2011-04-14 00:33:58

+0

是的,我相信。 – sourcedelica 2011-04-15 10:53:13

+0

谢谢,这在我的Groovy项目中影响了我。我猜想这不会发生在Java中,因为没有GString类型。 – Sion 2015-11-25 17:06:43

23

因为使用$导致Groovy来解释注释参数作为一个GString的,你会得到一个编译错误。您可以转义\ $或使用单引号。

+0

这应该被标记为接受的答案 – 2016-05-29 20:04:38

相关问题