2017-08-20 47 views
-2

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

请添加堆栈跟踪。 – davidxxx

+0

是的,请添加stacktrace。 required = false只是禁用依赖检查。 如果您稍后在代码中引用'FileWriter'对象,则会得到NullPointer异常。 –

+1

如果一个变量是'null',并且你试图调用一个方法,为什么你会惊讶地发现'NullPointerException'? –

回答

-1
public void writeToFile(String message) { 
     fileWriter.write(message); // this is throwing the error as the bean is comments in the XML file.. 
    } 

错误因为没有bean注入到fileWriter如果bean不会被注入,那么在使用它之前尝试验证对象是否为空。

public void writeToFile(String message) { 
     if (fileWriter!=null) 
     fileWriter.write(message); // this is throwing the error as the bean is comments in the XML file.. 
    } 

另一种方法是使用@PostConstruct,例如:

@PostConstruct 
public void initBean(){ 
    if (fileWriter ==null) fileWriter = new SomeFileWriter(); 
} 

在这种情况下,没有必要评价fileWriterwriteToFile方法

您也可以使用init方法,而不是@PostConstruct

想要这样:

<bean id="log" class="com.rajkumar.spring.Log" init-method="myInit"></bean> 

然后在myInit()方法尝试初始化您的空对象。

0

required=false是只让Spring容器依赖检查可选的,它避免了correpsonding豆未发现异常如..需要型豆“com.rajkumar.spring.FileWriter”不能被发现

请注意,注入的对象在这里仍然是null,因此您会看到NullPointerException

希望这有助于你。

0

尝试在您的类定义之上添加@Component Annotation。

@Component 
public class Log { 
... 

如果没有Spring将无法识别您的类在某处注入某些内容,并且您的字段将保持为空。您可能还想将ComponentScan添加到您的配置中。