我对Spring Bean还不熟悉,所以不理解在constructor-arg中使用ref的作用。为什么不能像这个例子一样再次使用value呢?
以下是TextEditor.java文件的内容:
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
以下是另一个依赖类文件SpellChecker.java的内容:
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
以下是MainApp.java文件的内容:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
以下是配置文件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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<constructor-arg ref="spellChecker"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
为什么不采用这种方式,直接使用spellChecker bean,而不是创建一个文本编辑器bean并引用另一个对象spellChecker?
在MainApp.java中
TextEditor te = (TextEditor) context.getBean("spellChecker");
如果我们使用它是因为两个对象属于不同的类,那么如果两个对象属于同一个类,我们可以省略ref吗?
另外,如果多个对象引用同一个对象,是必须为每个类创建一个bean并使用ref引用该对象,还是使用相同的bean但其scope=prototype?
SpellChecker sc = (SpellChecker) context.getBean("spellChecker");
而不是TextEditor te = (TextEditor) context.getBean("spellChecker");
?在你的例子中,TextEditor 除了将任务委托给 SpellChecker 外并没有做太多事情。然而,在一个真实的应用程序中,它会有更多的责任。 - asgs