2016-04-10 4 views
4

私は@Valueアノテーションを利用しようとしていますが、文字列変数をプロパティファイルから自動的に読み込みますが、運がありません。値は設定されておらず、nullです。ここでjava - Spring @Valueアノテーションでnullが返される

は私の設定です:

SendMessageController.java

@RestController 
public class SendMessageController { 

    @Value("${client.keystore.type}") 
    private static String keystoreType; 

    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST) 
    public ResponseEntity<SendMessageResponse> sendMessage(@Validated @RequestBody SendMessageRequest messageRequest) { 
    ....... 
    } 

application.properties

client.keystore.type=JKS 

残り-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 


    <context:component-scan base-package="org.example.controllers" /> 

    <context:property-placeholder location="classpath:application.properties"/> 

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> 
    <mvc:annotation-driven /> 

</beans> 

アプリケーションを実行してkeystoreType変数にアクセスしようとすると、常にnullになります。 私は何が間違っていますか?

+0

private static String keystoreType; @Value("${client.keystore.type}") public void setKeystoreType(String keystoreType) { SendMessageController.keystoreType = keystoreType; } 

または変更:

@Value("${client.keystore.type}") private static String keystoreType; 

に'@ Value'アノテーションの文は' import org.springframework.beans.factory.annotation.Value; 'ですか? –

+0

Springは何も 'static'を処理しません。あなたのフィールドはなぜ静的なのですか? – Savior

+0

大丈夫、変数を非静的にした後、すべて正常に動作します。ありがとう。 – Oleg

答えて

7

スプリングは静的フィールドに@Valueを直接注入できません。

あなたはこのような注釈付きのセッターを通じて価値を注入追加するか

:インポートを確認してくださいすることができ

@Value("${client.keystore.type}") 
private String keystoreType; 
+0

あなたの説明をありがとう、これは問題を解決しました – Oleg

+0

@Olegあなたは歓迎します、あなたは答えとしてそれをマークできますか? –

+0

タイムアウトを待って:) – Oleg

関連する問題