48

I have a groovy class where I wan to autowire a property value.

Eg:

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

With the addition of the the property-placeholder in my appliction context

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

The app.properties has a value set for "valueA" so in theory this should populate the String valueA in my class at runtime.

This setup works perfectly if I use a java class but not if I use a groovy class.

I get a compile error:

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

I just want to know if the above syntax is correct when using a groovy class and if not what is the correct syntax for autowiring the @Value parameter at runtime.

axtavt
  • 239,438
  • 41
  • 511
  • 482
Dion
  • 481
  • 1
  • 4
  • 3

2 Answers2

86

Use single quotes, ie.

public @Value('${valueA}') String valueA
sourcedelica
  • 23,940
  • 7
  • 66
  • 74
  • 1
    Is this because with double quotes you get a GString instead of a String and the substitution is done at the wrong time? – Michael Rutherfurd Apr 14 '11 at 00:33
  • Thanks, this affected me in my Groovy project. I suspect this doesn't happen in Java as there is no GString type. – Sion Nov 25 '15 at 17:06
  • 1
    This seems to work, but not when attempting to use a default value. `public @Value('${propertyName:defaultValue}') String valueA` In this scenario, 'defaultValue' is **always** used as the value for _propertyName_, even when overridden in a property file. The value in the property file is not used. – BrentR Mar 29 '16 at 11:21
33

since using a $ causes Groovy to interpret the annotation argument as a GString, you get a compile error. you can either escape \$ or use single quotes.

Andre Steingress
  • 4,381
  • 28
  • 28