@Autowired bean在另一個(gè)bean的構(gòu)造函數(shù)中引用時(shí)為null下面顯示的是一段代碼,我嘗試引用我的ApplicationProperties bean。當(dāng)我從構(gòu)造函數(shù)引用它時(shí)它是null,但是當(dāng)從另一個(gè)方法引用它時(shí)它很好。到目前為止,我在其他類中使用這個(gè)自動(dòng)裝配的bean沒有任何問(wèn)題。但這是我第一次嘗試在另一個(gè)類的構(gòu)造函數(shù)中使用它。在下面的代碼片段中,當(dāng)從構(gòu)造函數(shù)調(diào)用時(shí),applicationProperties為null,但在convert方法中引用時(shí)則不是。我錯(cuò)過(guò)了什么@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貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
自動(dòng)裝配在構(gòu)造對(duì)象之后發(fā)生。因此,在構(gòu)造函數(shù)完成之后才會(huì)設(shè)置它們。
如果需要運(yùn)行一些初始化代碼,您應(yīng)該能夠?qū)?gòu)造函數(shù)中的代碼拉入方法中,并使用該方法注釋該方法@PostConstruct
。

PIPIONE
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
要在構(gòu)造時(shí)注入依賴項(xiàng),您需要將構(gòu)造函數(shù)標(biāo)記為@Autowired
annoation。
@Autowiredpublic DocumentManager(IApplicationProperties applicationProperties) { this.applicationProperties = applicationProperties; startOOServer();}
添加回答
舉報(bào)
0/150
提交
取消