2015-05-17 49 views
1

我在使用@PropertySource一些麻煩,使用env.getProperty(..)當我得到一個NPE 沒有任何人有任何見解春天 - @PropertySource,得到一個NPE;(

我的環境:

  • ? JDK/JRE:1.6.0_06
  • 操作系統:Linux Mint的13
  • 春:4.1.6.RELEASE

堆棧跟蹤:

Exception in thread "main" java.lang.NullPointerException 
    at com.mycompany.app.ExpressiveConfig.main(ExpressiveConfig.java:33) 

屬性文件/src/main/resources/com/mycompany/app/app.properties

disc.title=Sgt.PeppersLonelyHeartsClubBand 
disc.artist=TheBeatles 

我的配置類:

package com.mycompany.app; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.*; 
import org.springframework.core.env.Environment; 

@PropertySource("classpath:/com/mycompany/app/app.properties") 
public class ExpressiveConfig { 

    @Autowired 
    Environment env; 

    @Bean 
    public App get() { 
     return new App("hello", env.getProperty("disc.artist")); 
    } 

    public static void main(String args[]) { 
     App a = new ExpressiveConfig().get(); 
    } 

} 

模型類:

package com.mycompany.app; 

import org.springframework.stereotype.Component; 

public class App { 

     private final String title; 
     private final String artist; 

     public App(String title, String artist) { 
     this.title = title; 
     this.artist = artist; 
     } 

     public String getTitle() { 
     return title; 
     } 

     public String getArtist() { 
     return artist; 
     } 
} 

Faile d嘗試:

  1. 我曾嘗試使用該文件與@PropertySource註釋玩耍,例如:前綴和絕對路徑屬性文件。 在類路徑之前刪除反斜槓eg/@ PropertySource(「classpath:com/mycompany/app/app.properties」)。 將屬性文件放在不同的位置。

  2. 我也試過使用@PropertySources也包含@PropertySource註釋。

  3. 我說:

    @Bean 公共靜態PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){ 返回新PropertySourcesPlaceholderConfigurer(); }

任何幫助/建議非常感謝!

+0

你是如何初始化ExpressiveConfig的? – shruti1810

+0

您測試的Hava: '@PropertySource(「classpath:app.properties」)'? –

回答

1

Spring只會將依賴注入到它自己管理的bean中。由於你自己創建了這個實例(new ExpressiveConfig()),所以不會執行依賴注入,因爲Spring實際上完全不涉及。

您需要使用該類型的bean定義創建應用程序上下文,並從那裏檢索實例。

要做到這一點,請將您的ExpressiveConfig註釋爲彈簧@Configuration,然後將其替換爲AnnotationConfigApplicationContext,而不是將其自己實例化。然後,您將能夠從getBean(...)的上下文中檢索您的bean。

+0

哇!感謝您的及時答覆!奇蹟般有效!! –

+0

很高興聽到它。如果它解決了您的問題,請接受答案。 –