Archive for the ‘Dependency Injection’ Category

silly problems with Spring @Value ‘${}’ with IoC injection

February 23, 2016 Leave a comment

hit some basic problems with Spring injection today worth noting for others

I was trying out @Value injection today in spring and hit some basic issues

1. when you use @Value in groovy and spring – despite the fact that you might want to use a ${} expression, you cant wrap this in “” which you might expect. The Groovy compiler gets in a huff and declares the the value is not a String (technically its a GString in groovy).

to make this work in groovy you have write something like (note single ”)

@Value ('${}')

This is counter intuitive if you are used to the normal “” Gstring interpolation in Groovy. To make it work with “” you have to try

@Value ("${}".toString())

or just use the ” as previously shown.

2. second issue: if injecting values from in root of your classpath , then note that the properties values in that file default to string, so `x.y.z=”hi”` will return a string including the quotes, which is not what you expect. just leave the strings unadorned to inject correctly.

3. then, if you use param injection alone like this

void setHost ( @Value ('${}') String host)

then you get a null injection (not sure why). To fix this, either

a) move the

@Value ('${}'

to method level, or

b) use @autowired at method level and leave the

@Value ('${}')

at parameter level as well,  to get the injection to occur.

It’s these small nuances that take so much time, hopefully someone else will benefit and save a couple of hours.

4. Lastly, you can lookup properties using the Spring Environment like this. Just use the @Autowired on method or constructor, and do the lookup /type conversion using the env.getRequiredProperty call like this

class Props {

    private Map props = [:]
    boolean jmxEnabled
    String host

    @Autowired  //test inject the env
    Props (Environment env) {
        jmxEnabled = env.getRequiredProperty("org.softwood.jmx", Boolean.class)


    //format either use Autowired for method and @value on param
    // or just @value as method injection will work
    void setHost ( @Value ('${}') String host)  {

        assert host
        println "set host by injection" = host
        props[host] = host

%d bloggers like this: