0

I am trying to understand why my autowired @Value("${delimiter}") property is not working. The framework finds the .properties file but does not map the delimiter property.

Tested.java

public class Tested{

    @Value("${delimiter}")
    protected String delimiter;

}

Tester.java

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = {"/Tester-context.xml"} )

public class Tester{

 @Value("${delimiter}")   
 protected String delimiter;

 @Test    
 public void test() {         
      fail("Not yet implemented");    
 }  

}

src/test/resources/Tester-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans" 
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath*:test.properties" />

</beans>

WEB-INF/classes/test.properties

delimiter = ||| 

Exception message snippet

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.Tester.delimiter; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'delimiter' in string value "${delimiter}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 28 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'delimiter' in string value "${delimiter}" ...
Stephen Isienyi
  • 1,292
  • 3
  • 17
  • 29

2 Answers2

1

With maven the resources being used by the tests are the one placed in the resources folder, typically src\test\resources

In your case move the test.properties file to the src\test\resources folder.

This answer to a similar question shows the default maven behavior.

Community
  • 1
  • 1
Paizo
  • 3,986
  • 30
  • 45
0

Each context:property-placeholder creates a new instance of PropertyPlaceholderConfigurer - it gets messy easily. You should have one such thing per application and on application level.

P.S.: @Value has been available since Spring 3.0

Daniel Boncioaga
  • 336
  • 1
  • 13