cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Using @Value to get properties

Former Member
0 Likes
595

I'm putting together a unit test and trying to get a smallish chunk of the Spring context to confirm DI wiring is all good with annotation-driven config and do some testing.

For some reason I can't get @Value("${my.property}") injection to work. The expression below is working ('defaultValue' is the result). I've tried setting a @PropertySource on my unit test to no avail in different ways.

 class Banana {
     public Banana(@Value("${my.property:defaultValue}") final String myProperty) {
       // do stuff
     }
 }


Has anyone had any luck applying this approach for getting their properties in this way?

Accepted Solutions (0)

Answers (3)

Answers (3)

Former Member
0 Likes

Thanks for the replies - it turns out it's somewhat of a Spring framework issue when you use the "${foo}" placeholders. You have to have a PropertySourcesPlaceholderConfigurer bean or it won't resolve the expressions to be used via injection for you despite having those properties on the classpath. The key items from below is the addition of WSClientIntegrationTest.Config.class into the ContextConfiguration and the simple bean inside the test class. Naturally this is best placed in a more higher level base class of sorts for a test context config.

If this helps someone in the future, the general idea is:

 @RunWith(SpringRunner.class)
 @ContextConfiguration(
         classes = {WSClientIntegrationTest.Config.class, WSClient.class, WSMarshaller.class, WSMessageSender.class}
 )
 @TestPropertySource
 public class WSClientIntegrationTest {
 
     @Configuration
     static class Config {
         @Bean
         public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
             return new PropertySourcesPlaceholderConfigurer();
         }
     } // etc
 }
0 Likes
ravi_tavva
Associate
Associate
0 Likes

Justin, Did you put "my.property" and its corresponding value in your local.properties?