@Value 自动装配问题

@Value autowire problems

我想了解为什么我的自动装配 @Value("${delimiter}") 属性 不起作用。框架找到 .properties 文件但未映射分隔符 属性.

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 = ||| 

异常消息片段

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

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

P.S.: @Value 自 Spring 3.0

以来可用

对于 Maven,测试使用的资源是放置在 resources 文件夹中的资源,通常是 src\test\resources

在您的情况下,将 test.properties 文件移动到 src\test\resources 文件夹。

类似问题的answer显示了默认的 maven 行为。