@Autowired bean在另一個bean的構造函數中引用時為null下面顯示的是一段代碼,我嘗試引用我的ApplicationProperties bean。當我從構造函數引用它時它是null,但是當從另一個方法引用它時它很好。到目前為止,我在其他類中使用這個自動裝配的bean沒有任何問題。但這是我第一次嘗試在另一個類的構造函數中使用它。在下面的代碼片段中,當從構造函數調用時,applicationProperties為null,但在convert方法中引用時則不是。我錯過了什么@Componentpublic class DocumentManager implements IDocumentManager {
private Log logger = LogFactory.getLog(this.getClass());
private OfficeManager officeManager = null;
private ConverterService converterService = null;
@Autowired
private IApplicationProperties applicationProperties;
// If I try and use the Autowired applicationProperties bean in the constructor
// it is null ?
public DocumentManager() {
startOOServer();
}
private void startOOServer() {
if (applicationProperties != null) {
if (applicationProperties.getStartOOServer()) {
try {
if (this.officeManager == null) {
this.officeManager = new DefaultOfficeManagerConfiguration()
.buildOfficeManager();
this.officeManager.start();
this.converterService = new ConverterService(this.officeManager);
}
} catch (Throwable e){
logger.error(e);
}
}
}
}
public byte[] convert(byte[] inputData, String sourceExtension, String targetExtension) {
byte[] result = null;
startOOServer();
...以下是ApplicationProperties的s片段...@Componentpublic class ApplicationProperties implements IApplicationProperties {
/* Use the appProperties bean defined in WEB-INF/applicationContext.xml
* which in turn uses resources/server.properties
*/
@Resource(name="appProperties")
private Properties appProperties;
public Boolean getStartOOServer() {
String val = appProperties.getProperty("startOOServer", "false");
if( val == null ) return false;
val = val.trim();
return val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on") || val.equalsIgnoreCase("yes");
}
2 回答

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
自動裝配在構造對象之后發生。因此,在構造函數完成之后才會設置它們。
如果需要運行一些初始化代碼,您應該能夠將構造函數中的代碼拉入方法中,并使用該方法注釋該方法@PostConstruct
。

PIPIONE
TA貢獻1829條經驗 獲得超9個贊
要在構造時注入依賴項,您需要將構造函數標記為@Autowired
annoation。
@Autowiredpublic DocumentManager(IApplicationProperties applicationProperties) { this.applicationProperties = applicationProperties; startOOServer();}
添加回答
舉報
0/150
提交
取消