@Value自动布线问题



我试图理解为什么我的autowired @Value("${delimiter}")属性不工作。框架找到.properties文件,但不映射分隔符属性。

Tested.java

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

Tester.java

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

公共类Tester{

 @Value("${delimiter}")   
 protected String delimiter;
 @Test    
 public void test() {         
      fail("Not yet implemented");    
 }  

}

src/测试/资源/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 = ||| 

异常消息片段

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}" ...

对于maven,测试使用的资源是放置在resources文件夹中的资源,通常是srctestresources

在您的情况下,移动test.properties文件到srctestresources文件夹。

这个类似问题的答案显示了默认的maven行为。

每个context:property-placeholder创建一个PropertyPlaceholderConfigurer的新实例——它很容易变得混乱。每个应用程序和应用程序级别都应该有一个这样的东西。

注:: @Value从Spring 3.0开始就可用了

最新更新