我正在尝试使用注释来连接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'? –