[英]What is the use of ref in constructor-arg in java spring beans?
我是spring bean的新手,所以我沒有在構造函數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 textEditor並引用另一個對象spellChecker,你可以直接使用spellChecker bean嗎?
在MainApp.java中
TextEditor te = (TextEditor) context.getBean("spellChecker");
如果我們使用它,因為兩個對象都在不同的類中,那么如果兩者都在同一個類中,我們可以取消引用嗎?
此外,如果多個對象引用同一個對象,是否有必要為每個類創建一個bean並使用ref引用此對象或使用相同的bean但使用scope = prototype?
Spring bean的ref
屬性引用了另一個在某處實例化的Spring bean。 在你的情況下, SpellChecker
是一個Spring-singleton bean,你想“注入”另一個TextEditor
類型的Spring bean。 ref
很有用的原因是你的大多數bean都將是Singleton,除非你希望每個請求,每個會話等創建它們。默認范圍是Singleton。
此外,如果多個對象引用同一個對象,是否有必要為每個類創建一個bean並使用ref引用此對象或使用相同的bean但使用scope = prototype?
我認為你想說“多個類引用同一個對象”。 在這種情況下,您在類中所做的只是聲明對該bean(或對象)的“引用”。 然后你將“bean”注入到依賴類(或bean)中。
您可以閱讀有關Spring bean引用的更多信息。
此外,如果多個對象引用同一個對象,是否有必要為每個類創建一個bean並使用ref引用此對象或使用相同的bean但使用scope = prototype?
如果多個類引用同一個對象,則可以使用單例作用域(如果未在bean中指定scope屬性,則為默認值)。 在單例中,多個對象共享單個對象。它們僅創建對單例對象的本地引用。 它們不會每次都初始化一個新對象。 因此,使用的堆內存不多。
然而,在原型中,每個對象都創建一個新的內部對象(即在本地初始化一個新的對象引用)。 因此,創建許多對象會產生開銷,因此會加載堆。
它完全取決於您的應用程序,您希望使用哪個范圍。 但通常,在Web應用程序中,人們使用Singleton作為DAO Connection類,這樣連接過程只發生一次,並被引用DAOConnection類的所有類重用。
他們使用原型進行POJO類。 這樣每次類引用它時都會創建一個新對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.