代码之家  ›  专栏  ›  技术社区  ›  breakline

Spring读取属性文件,但值为空

  •  0
  • breakline  · 技术社区  · 10 年前

    我不太明白这里的问题。我正在尝试在Spring应用程序中使用属性文件。文件似乎已被读取,但如果我尝试读取值,则会得到空值。

    这是我的上下文xml的一部分:

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aws-context="http://www.springframework.org/schema/cloud/aws/context" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/cloud/aws/context
    http://www.springframework.org/schema/cloud/spring-cloud-aws-context.xsd">
    
    <tx:annotation-driven />
    
    <context:component-scan base-package="my.package" />
    
    <context:annotation-config />
    
    <context:property-placeholder location="classpath:test.properties" />
    
    <!-- OTHER STUFF HERE -->
    </beans>
    

    我有考试。src/main/resources下的属性

    当我尝试这样运行时:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath*:META-INF/spring/context-test.xml")
    public class SimpleTest {
    
        @Autowired
        private ApplicationContext context;
    
        @Autowired
        private Environment environment;
    
        @Test
        public void test() throws Exception {
            System.out.println(environment);
            System.out.println(environment.getProperty("my.test"));
        }
    }
    

    输出将为:

    StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[systemProperties,systemEnvironment]}
    null
    

    所以我想除了系统属性之外,我应该在“propertySources”中看到一些东西,对吗?

    如果我将xml行更改为:

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

    我得到一个FileNotFound异常,这意味着文件本身已加载?那么为什么我不能从中加载属性呢?

    在测试中。属性我只有这个:

    my.test=123456
    

    这里可能有什么问题?

    1 回复  |  直到 10 年前
        1
  •  1
  •   Rens Verhage    10 年前

    属性占位符不会自动向环境公开属性。您应该这样注入您的属性:

    @Value("${my.test}")
    private String myTest;
    
    推荐文章