2017-08-09 13 views
0

mavenプロジェクトでSpringフレームワークを使用して渡された入力に基づいてプロパティファイルを読み込む必要があります。プロパティファイルとアプリケーションコンテキストがsrc/main/resourcesにあります@Autowired Nullポインタ例外を使用してプロパティファイルを読み取る

プロパティファイルを挿入するために環境APIを使用しようとしています。

コード:しかし、私はラインでnullポインタ例外を取得しておく

@Component 
@Configuration 
@PropertySource("classpath:GeoFilter.properties") 
public class CountryGeoFilter { 

    @Autowired 
    public Environment environment; 

    public GeoFilterStore getCountryGeoFilter(String country) throws 
CountryNotFoundException, IOException { 

    GeoFilterStore countryFilterStore = new GeoFilterStore(); 

    String value = environment.getProperty(country); 
    if (value == null) { 
     throw CountryNotFoundException.getBuilder(country).build(); 
    } 
    String[] seperateValues = value.split(":"); 

    countryFilterStore.setGameStore(isTrueValue(seperateValues[0])); 

    countryFilterStore.setVideoStore(isTrueValue(seperateValues[1])); 
    return countryFilterStore; 
    } 

    private boolean isTrueValue(String possibleTrueValue) { 
     return !possibleTrueValue.equals("No") && 
     !possibleTrueValue.equals("N/A"); 
    } 
} 

"文字列値= environment.getProperty(国);"

私は次のよう

try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");) { 
     CountryGeoFilter objGeo = (CountryGeoFilter) context.getBean("geoFilter"); 
     GeoFilterStore responseStore = objGeo.getCountryGeoFilter(country); 
    } 

マイapplicationContext.xmlを内の関数を呼び出すしています(SRC /メイン/リソース)

<bean id="geoFilter" 
    class="com.package.CountryGeoFilter" /> 

注:私は他のクラスとプロパティを持っています私が同じことをして、beanがapplicationContext.xmlで宣言する必要があるファイル。

私は春には新しく、どこが間違っているのかわからない。どんな助けもありがとう。

+0

は、あなたが正しいです 'CountryGeoFilter' –

答えて

0

applicationContext.xmlのすべてを見ると便利です。

applicationContext.xmlを見ずに、私の答えはちょうど推測です。

CountryGeoFilterを含むパッケージを「スキャン」していない可能性があります。

<context:component-scan base-package="com.geo" />

CountryGeoFilter@Component注釈を持っている:CountryGeoFilterがパッケージにあった場合は、あなたの春の設定ファイルは、のようなものが含まれている必要がありますcom.geo。 Springがクラス定義を認識していない限り、この注釈は無意味です。このアノテーションを含むクラスを認識するために、Springは<context:component-scan/>要素で識別されるパッケージをスキャンします。

このクラス定義をスキャンすると、このクラスのシングルトンインスタンスであるBeanが作成されます。インスタンスを作成した後、あなたのEnvironmentメンバーをオートワイヤします。

このメカニズムの追加の例はhereです。

+0

の上にComponent' @'必要はありませんと仮定します。私はパッケージをスキャンしていませんでした。ありがとう – hmahboob

0
  1. NPEは、環境がヌル、つまり正しく注入されなかった場合に起こります。
  2. また、プロパティファイルに ":"をエスケープしていることを確認してください。

チェックは例を働いた:https://github.com/daggerok/spring-property-source-example

関連する問題