2017-08-20 106 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添加到您的配置中。