我在使用@PropertySource时遇到了一些问题,我在使用env.getProperty(..)时得到了一个NPE。有人有洞察力吗?
我的环境:
堆叠痕迹:
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注释,例如使用文件:前缀和属性文件的绝对路径。在类路径eg/@PropertySource("classpath:com/mycompany/app/app.properties").之前删除反斜杠将属性文件放在不同的位置。@PropertySources注释的@PropertySource。任何帮助/建议都非常感谢!!
发布于 2015-05-17 09:37:44
Spring只会将依赖项注入到它自己管理的bean中。由于您是自己创建该实例(new ExpressiveConfig()),因此将不会执行依赖项注入,因为Spring实际上根本不涉及。
您需要为该类型创建一个具有bean定义的应用程序上下文,并从其中检索实例。
要做到这一点,请将ExpressiveConfig注释为spring @Configuration,然后不实例化它,只需将该类传递给AnnotationConfigApplicationContext即可。然后,您将能够使用getBean(...)从上下文中检索bean。
https://stackoverflow.com/questions/30285382
复制相似问题