【发布时间】:2015-07-28 21:44:16
【问题描述】:
我在使用 @PropertySource 时遇到了一些问题,我在使用 env.getProperty(..) 时遇到了 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;
}
}
尝试失败:
我尝试过使用
@PropertySource注释,例如使用文件:属性文件的前缀和绝对路径。 在类路径之前删除反斜杠,例如/@PropertySource("classpath:com/mycompany/app/app.properties")。 将属性文件放在不同的位置。我也尝试过使用包含
@PropertySource注释的@PropertySources。-
我已添加:
@豆 公共静态 PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 返回新的 PropertySourcesPlaceholderConfigurer(); }
非常感谢任何帮助/建议!
【问题讨论】:
-
你是如何初始化 ExpressiveConfig 的?
-
你测试过:
@PropertySource("classpath:app.properties")?