2015-05-17 43 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

很高兴听到它。如果它解决了您的问题,请接受答案。 –