我正在嘗試使用註釋來連接bean。當bean.xml中沒有配置文件時,我得到一個空指針異常..我期望required = false屬性來解決這個問題。這是一個公平的期望嗎?如果是這樣,爲什麼它仍然拋出例外,甚至如果我設置需要爲假的失蹤豆...自動裝配所需的豆
package com.rajkumar.spring;
import org.springframework.beans.factory.annotation.Autowired;
public class Log {
private ConsoleWriter consoleWriter;
private FileWriter fileWriter;
@Autowired
public void setConsoleWriter(ConsoleWriter consoleWriter) {
this.consoleWriter = consoleWriter;
}
@Autowired(required=false)
public void setFileWriter(FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
public void writeToFile(String message) {
fileWriter.write(message); // this is throwing the error as the bean is comments in the XML file..
}
public void writeToConsole(String message) {
consoleWriter.write(message);
}
}
我的beans.xml低於..
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="log" class="com.rajkumar.spring.Log"></bean>
<bean id="consoleWriter"
class="com.rajkumar.spring.ConsoleWriter">
</bean>
<!-- <bean id="fileWriter" class="com.rajkumar.spring.FileWriter"></bean> -->
<context:annotation-config></context:annotation-config>
</beans>
請添加堆棧跟蹤。 – davidxxx
是的,請添加stacktrace。 required = false只是禁用依賴檢查。 如果您稍後在代碼中引用'FileWriter'對象,則會得到NullPointer異常。 –
如果一個變量是'null',並且你試圖調用一個方法,爲什麼你會驚訝地發現'NullPointerException'? –