0

ここの問題がよくわかりません。Spring アプリケーションでプロパティ ファイルを使用しようとしています。ファイルは読み取られるようですが、値を読み取ろうとするとnullになります。

これは私のコンテキスト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 の下に test.properties があります

次のように実行しようとすると:

@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 例外が発生しますか? では、なぜそこからプロパティを読み込めないのでしょうか?

test.properties には、これだけがあります。

my.test=123456

ここで何が問題になる可能性がありますか?

4

1 に答える 1

1

プロパティ プレースホルダーは、プロパティを環境に自動的に公開しません。次のようにプロパティを注入する必要があります。

@Value("${my.test}")
private String myTest;
于 2015-07-18T13:48:22.440 に答える