Spring: @Value and @TestPropertySource


Recently I had a few issues getting this working in a Spring boot application.  Here’s a simple sample.  Make sure the SomeTestProperties.properties is in the resources folder under test🙂

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SomeTest.class)
@TestPropertySource("classpath:SomeTestProperties.properties")
//@TestPropertySource(properties = {"Text=abc"})
@Configuration
public class PropertyLoadTest {
    @Autowired
    private Environment environment;

    @Value("${Text}")
    private String text;

    static class Config {
        @Value("${Text}")
        private String text;

        public String getText() {
            return text;
        }
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    }

    @Test
    public void propertyLoadTest() {
        System.out.println("Text= " + this.environment.getProperty("Text"));
        System.out.println("Text= " + text);
    }
}

~ by mdavey on April 12, 2016.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: