I'm new to spring beans, so I don't get the use of ref in constructor-arg. Why not use value again like in this example here,
Here is the content of TextEditor.java file:
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();
}
}
Following is the content of another dependent class file SpellChecker.java:
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file:
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();
}
}
Following is the configuration file Beans.xml which has configuration for the constructor-based injection:
<?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>
Here, why not do it this way where, instead of creating a bean textEditor and referencing another object spellChecker, you can directly use the spellChecker bean?
In MainApp.java
TextEditor te = (TextEditor) context.getBean("spellChecker");
If we use it because both the objects are in different classes, then can we do away with ref if both are in same class?
Also if multiple objects refer to same object, is it necessary to create a bean for each of those classes and use ref to refer to this object or use same bean but with scope=prototype?
SpellChecker sc = (SpellChecker) context.getBean("spellChecker");
instead ofTextEditor te = (TextEditor) context.getBean("spellChecker");
? Here in your example, TextEditor doesn't do much except delegate the task to SpellChecker. However, in a real application, there will be more responsibilities. – Phina