自动装配所需的bean

时间:2017-08-20 15:49:15

标签: java spring

我正在尝试使用Annotations连接bean。当beans.xml配置文件中没有bean时,我得到一个空指针异常..我希望required = false属性来解决这个问题..是公平的期望?如果是这样,为什么它仍然会抛出异常,即使我将缺少的bean设置为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);
    }


}

My 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>

3 个答案:

答案 0 :(得分:0)

required=false只是使spring容器依赖项检查可选,并且它避免了相应的bean找不到异常,例如.. 需要一个类型为&#39; com.rajkumar.spring.FileWriter&#39;的bean。无法找到

请注意,此处注入的对象仍为null,因此您看到NullPointerException

希望这会对你有所帮助。

答案 1 :(得分:0)

尝试在类定义上方添加@Component Annotation。

private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add("NextStation: " + textBox1.Text);
        listBox1.Items.Add("Station: " +textBox1.Text);
    }

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

答案 2 :(得分:-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,然后在使用之前尝试验证对象是否为null。

  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();
}

在这种情况下,无需在fileWriter方法

上评估writeToFile

您也可以使用init方法代替@PostConstruct

像这样:

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

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

相关问题