【问题标题】:@Value autowire problems@Value 自动装配问题
【发布时间】:2015-10-02 17:50:02
【问题描述】:

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

Tested.java

public class Tested{

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

}

Tester.java

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

公共类测试者{

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

异常信息 sn-p

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

【问题讨论】:

  • 你应该尝试将test.properties文件放在测试资源下src\test\resources
  • 它现在可以工作了。谢谢@Paizo
  • 我添加了一个更完整的答案,以帮助其他查看此问题的人,如果它解决了您的问题,请接受它。
  • 听起来不错,我现在接受了

标签: spring unit-testing autowired


【解决方案1】:

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

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

这个answer 与一个类似的问题显示了默认的maven 行为。

【讨论】:

    【解决方案2】:

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

    P.S.:@Value 从 Spring 3.0 开始可用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2011-12-29
      相关资源
      最近更新 更多