[英]Spring autowire byName not working as expected
Spring autowire 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年编写!)
基本上,属性是与Bean关联的命名属性,可以通过在Bean上调用适当的方法来读取或写入属性。 因此,例如,bean可能具有代表其前景色的
foreground
属性。 可以通过调用Color getForeground()
方法读取此属性,并通过调用void setForeground(Color c)
方法来更新此属性。来源JavaBeans规范。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.