[英]Spring - @PropertySource, getting an NPE ;(
我在使用@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
批注,例如使用file:前綴和屬性文件的絕對路徑。 在類路徑之前添加反斜杠,例如//PropertySource("classpath:com/mycompany/app/app.properties“)。 將屬性文件放在不同的位置。
我已經使用也嘗試@PropertySources
包含@PropertySource
注解了。
我已經添加:
@Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){return new PropertySourcesPlaceholderConfigurer(); }
任何幫助/建議非常感謝!
Spring只會將依賴項注入到它自己管理的bean中。 由於您是自己創建實例( new ExpressiveConfig()
),因此不會執行依賴項注入,因為實際上根本不涉及Spring。
您需要使用該類型的bean定義創建一個應用程序上下文,然后從那里檢索實例。
為此,將您的ExpressiveConfig
注釋為spring @Configuration
,然后將其傳遞給AnnotationConfigApplicationContext
,而不是實例化自己。 然后,您可以使用getBean(...)
從上下文中檢索bean。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.