Spring 自动装配 byName 未按预期工作

Spring autowire byName not working as expected

Spring 自动装配 byName 未按预期工作。

public class SpellChecker {
    public SpellChecker() {
        System.out.println("Inside SpellChecker constructor." );
    }

    public void checkSpelling() {
        System.out.println("Inside checkSpelling." );
    }
}

public class TextEditor {

       private SpellChecker spellChecker1;
       private String name;

       public void setSpellChecker( SpellChecker spellChecker1 ){
          this.spellChecker1 = spellChecker1;
       }
       public SpellChecker getSpellChecker() {
          return spellChecker1;
       }
       public void setName(String name) {
          this.name = name;
       }
       public String getName() {
          return name;
       }

   public void spellCheck() {
       System.out.println(" TextEditor name is " +name);
      spellChecker1.checkSpelling();
   }
}

public class TextEditorMain {

    public static void main(String args[]) throws InterruptedException{

        ApplicationContext context = new 
        ClassPathXmlApplicationContext("Beans.xml"); 
        TextEditor tEditor = (TextEditor) context.getBean("textEditor");
        tEditor.spellCheck();   
    }
}

Spring beans 配置:

<bean id = "spellChecker1" class = "com.spring.beans.SpellChecker">
</bean>

<bean id = "textEditor" class = "com.spring.beans.TextEditor" autowire="byName">
   <property name = "name" value = "text1"/>
</bean>

当我将 spellChecker1 作为 bean id 时,它不起作用。下面是控制台 o/p,

Inside SpellChecker constructor.
 TextEditor name is text1
Exception in thread "main" java.lang.NullPointerException
    at com.spring.beans.TextEditor.spellCheck(TextEditor.java:26)
    at com.spring.main.TextEditorMain.main(TextEditorMain.java:15)

Bean id 和引用名称都相同 spellChecker1 但仍然无法正常工作。但奇怪的是,如果我将 xml 中的 bean id 从 spellChecker1 更改为 spellChecker 代码正在运行并在 o/p,

以下给出
Inside SpellChecker constructor.
 TextEditor name is text1
Inside checkSpelling.

那么为什么我使用 spellChecker1 时没有添加依赖项?

它实际上按设计工作。您的 属性 被命名为 spellChecker 而不是 spellChecker1。您有一个名为 spellChecker1.

字段

字段的名称与属性的名称不同。 属性 的名称由 class 上可用的 getset 方法定义。因为你有一个 setSpellChecker(和相应的 getter)所以有一个名为 spellChecker.

属性

所有这些都写在 JavaBeans Specification 中(写于 1998 年的某个地方!)

Basically properties are named attributes associated with a bean that can be read or written by calling appropriate methods on the bean. Thus for example, a bean might have a foreground property that represents its foreground color. This property might be read by calling a Color getForeground() method and updated by calling a void setForeground(Color c) method.

Source the JavaBeans Specification.