我是Spring bean的新手,所以我沒有在構造函數arg中使用ref。爲什麼不利用價值再像在這裏這個例子中,java spring bean中constructor-arg中ref的用法是什麼?
這裏是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>
在這裏,爲什麼不能做這種方式在哪裏,而不是創建一個bean文本編輯和引用另一個對象的拼寫檢查器,可以直接使用spellChecker bean?
在MainApp.java
TextEditor te = (TextEditor) context.getBean("spellChecker");
如果我們使用它,因爲兩個對象在不同的班級,這樣我們才能與裁判做掉,如果兩者在同一個班?
此外,如果多個對象引用同一個對象,是否有必要爲每個類創建一個bean,並使用ref來引用這個對象或使用相同的bean,但使用scope = prototype?
你的意思是'SpellChecker sc =(SpellChecker)context.getBean(「spellChecker」);'而不是'TextEditor te =(TextEditor)context.getBean(「spellChecker」);'?在你的例子中,除了[delegate](https://en.wikipedia.org/wiki/Delegation_pattern)任務給SpellChecker之外,TextEditor並沒有做太多的工作。但是,在實際應用中,會有更多的責任。 – asgs