Problem with spring @Value annotation. 1


Hi. Today I expirienced problem with @Value annotation in spring.
This annotation can be used to inject value from properties files in spring based applications.
I will show you a typical use case of this annotation, the problem I encountered and how I dealt with it.

foo.properties:

address=Warsaw

Foo.java:

package com.raphaelsolarski.value;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:foo.properties")
public class Foo {

    @Value("${address}")
    private String address;

    public String getAddress() {
        return address;
    }

}

FooTest.java:

package com.raphaelsolarski.value;

import com.raphaelsolarski.value.config.Config;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class FooTest {

    @Autowired
    private Foo foo;

    @Test
    public void shouldReturnPropertyValue() throws Exception {
        String actual = foo.getAddress();
        String expected = "Warsaw";
        Assert.assertEquals(expected, actual);
    }

}

The test will fail with the following error:

org.junit.ComparisonFailure: 
Expected :Warsaw
Actual   :${address}

There is a simple solution. We have to declare a PropertySourcesPlaceholderConfigurer bean somewhere in spring configuration of our application.

Config.java

package com.raphaelsolarski.value.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan("com.raphaelsolarski.value")
public class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

github-icon Full code on github.com


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Problem with spring @Value annotation.