Spring Autowiring 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 bean 配置:
<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
的字段。
字段 的名称与属性 的名称不同。属性的名称由类中可用的 get
和 set
方法定义。因为您有一个 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 aColor getForeground()
method and updated by calling avoid setForeground(Color c)
method.Source the JavaBeans Specification.
关于java - Spring autowire byName 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46143482/