Dependency Injection in Spring
• Dependency Injection (DI) is a design pattern
that removes the dependency from the
programming code so that it can be easy to
manage and test the application. Dependency
Injection makes our programming code
loosely coupled.
• Let's write a code without following IOC and
DI.
Dependency Injection in Spring
class Restaurant{
Tea tea = new Tea(); //creating instance
public void prepareDrink(){
tea.prepareTea(); }
}
class Tea{
public void prepareTea(){
// prepare tea
}
}
• Here you can see, there is dependency between Restaurant and Tea
classes. That means if you need to change the constructor of Tea class at
any point you need to change the object of Tea in Restaurant class too.
• Now see the following example with slide modification.
Dependency Injection in Spring
In this case we are not using tea object directly in Restaurant
class and thus they are loosely coupled. This is just an example
of loosely coupled design pattern. Spring framework use this
pattern by constructor or setter method which we can be
configured in a configuration file provided by spring.
class Restaurant{
Drink drink;
Restaurant(Drink drink){
this.drink = drink;
}
//Tea tea = new Tea(); //no need to create
this instance
public void prepareDrink(){
drink.prepareTea();
}
}
interface Drink{
public void
prepareTea();
}
class Tea implements Drink{
public void prepareTea(){
// prepare tea
}
}
Two ways to perform Dependency
Injection in Spring framework
• Spring framework provides two ways to inject
dependency
– By Constructor
– By Setter method
Dependency Injection by Constructor
Example
• We can inject the dependency by constructor.
The <constructor-arg>subelement
of <bean> is used for constructor injection.
Here we are going to inject
– primitive and String-based values
– Dependent object (contained object)
– Collection values etc.
Injecting primitive and string-based values
• Let's see the simple example to inject
primitive and string-based values. We have
created three files here:
– Employee.java
– applicationContext.xml
– Test.java
Employee.java
It is a simple class containing two fields id and name. There are four constructors and one method in this class.
package com.javaknowledge;
public class Employee {
private int id;
private String name;
public Employee() {System.out.println("def cons");}
public Employee(int id) {this.id = id;}
public Employee(String name) { this.name = name;}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
void show(){
System.out.println(id+" "+name);
}
}
applicationContext.xml
• We are providing the information into the bean by this file. The constructor-arg
element invokes the constructor. In such case, parameterized constructor of int
type will be invoked. The value attribute of constructor-arg element will assign the
specified value. The type attribute specifies that int parameter constructor will be
invoked.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e" class=" com.javaknowledge.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</beans>
Test.java
• Test.javaThis class gets the bean from the applicationContext.xml file and calls the show method.
package com.javaknowledge;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
• Output:10 null
Injecting string-based values
• If you don't specify the type attribute in the
constructor-arg element, by default string type
constructor will be invoked.
• You may pass integer literal and string both as
following....
<bean id="e" class="com.javaknowledge.Employee">
<constructor-arg value="10" type="int" ></constructor-arg>
<constructor-arg value=“Bari"></constructor-arg>
</bean>
• Output:10 Bari
Constructor Injection with Dependent
Object
• If there is HAS-A relationship between the
classes, we create the instance of dependent
object (contained object) first then pass it as
an argument of the main class constructor.
Here, our scenario is Employee HAS-A
Address. The Address class object will be
termed as the dependent object. Let's see the
Address class first:
Address.java
• This class contains three properties, one constructor and toString() method to return the values of these
object.
package com.javaknowledge;
public class Address {
private String city;
private String state;
private String country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return city+" "+state+" "+country;
}
}
Employee.java
• It contains three properties id, name and address(dependent object) ,two constructors and
show() method to show the records of the current object including the depedent object.
package com.javaknowledge;
public class Employee {
private int id;
private String name;
private Address address;//Aggregation
public Employee() {System.out.println("def cons");}
public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
applicationContext.xml
• The ref attribute is used to define the reference of another object, such way we are passing the
dependent object as an constructor argument.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<bean id="a1" class=" com.javaknowledge.Address">
<constructor-arg value=“Kakrile"></constructor-arg>
<constructor-arg value=“Dhaka"></constructor-arg>
<constructor-arg value=“Bangladesh"></constructor-arg>
</bean>
....
<bean id="e" class="com.javaknowledge.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value=“Bari"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and calls the show method.
package com.javaknowledge;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
Constructor Injection with Collection
Example
• We can inject collection values by constructor in spring framework. There can be
used three elements inside the constructor-arg element.
• It can be:
– list
– set
– map
• Each collection can have the applicationContext.xml file and List to Set in the
Question.java file. string based and non-string based values. In this example, we
are taking the example of Forum where One question can have multiple answers.
There are three pages:
– Question.java
– applicationContext.xml
– Test.java
• In this example, we are using list that can have duplicate elements, you may use
set that have only unique elements. But, you need to change list to set in
Question.java
• This class contains three properties, two constructors and displayInfo() method that prints the
information. Here, we are using List to contain the multiple answers.
package com.javaknowledge;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<String> answers;
public Question() {}
public Question(int id, String name, List<String> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<String> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
applicationContext.xml
• The list element of constructor-arg is used here to define the list.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="q" class="com.javaknowledge.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<constructor-arg>
<list>
<value>Java is a programming language</value>
<value>Java is a Platform</value>
<value>Java is an Island of Indonasia</value>
</list>
</constructor-arg>
</bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and calls the
displayInfo method.
package com.javaknowledge;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
Constructor Injection with Non-String Collection
(having Dependent Object) Example
• If we have dependent object in the collection, we can inject these
information by using the ref element inside the list, set or map.
• In this example, we are taking the example of Forum where One
question can have multiple answers. But Answer has its own
information such as answerId, answer and postedBy. There are four
pages used in this example:
– Question.java
– Answer.java
– applicationContext.xml
– Test.java
• In this example, we are using list that can have duplicate elements,
you may use set that have only unique elements. But, you need to
change list to set in the applicationContext.xml file and List to Set in
the Question.java file.
Question.java
• This class contains three properties, two constructors and displayInfo() method
that prints the information. Here, we are using List to contain the multiple
answers.
package com.javaknowledge;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<Answer> answers;
public Question() {}
public Question(int id, String name, List<Answer> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<Answer> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Answer.java
• This class has three properties id, name and by with constructor and toString()
method.
package com.javaknowledge;
public class Answer {
private int id;
private String name;
private String by;
public Answer() {}
public Answer(int id, String name, String by) {
super();
this.id = id;
this.name = name;
this.by = by;
}
public String toString(){
return id+" "+name+" "+by;
}
}
applicationContext.xml
• The ref element is used to define the reference of another bean. Here, we are using bean attribute
of ref element to specify the reference of another bean.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ans1" class=" com.javaknowledge.Answer">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="Java is a programming language"></constructor-arg>
<constructor-arg value="John"></constructor-arg>
</bean>
<bean id="ans2" class=" com.javaknowledge.Answer">
<constructor-arg value="2"></constructor-arg>
<constructor-arg value="Java is a Platform"></constructor-arg>
<constructor-arg value="Raji"></constructor-arg>
</bean>
<bean id="q" class=" com.javaknowledge.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<constructor-arg>
<list>
<ref bean="ans1"/>
<ref bean="ans2"/>
</list>
</constructor-arg>
</bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and calls the
displayInfo method.
package com.javaknowledge;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
Inheriting Bean in Spring
• By using the parent attribute of bean, we can
specify the inheritance relation between the
beans. In such case, parent bean values will be
inherited to the current bean.
• Let's see the simple example to inherit the
bean.
Employee.java
• This class contains three properties, three constructor and show() method to display the values.
package com.javaknowledge;
public class Employee {
private int id;
private String name;
private Address address;
public Employee() {}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
Address.java
package com.javaknowledge;
public class Address {
private String addressLine1,city,state,country;
public Address(String addressLine1, String city, String state, String country) {
super();
this.addressLine1 = addressLine1;
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
}
applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e1" class="com.javaknowledge.Employee">
<constructor-arg value="101"></constructor-arg>
<constructor-arg value=“A"></constructor-arg>
</bean>
<bean id="address1" class="com. javaknowledge.Address">
<constructor-arg value="21,Shantinagar"></constructor-arg>
<constructor-arg value=“Dhaka"></constructor-arg>
<constructor-arg value=“Dhaka"></constructor-arg>
<constructor-arg value=“Bangladesh"></constructor-arg>
</bean>
<bean id="e2" class="com. javaknowledge.Employee" parent="e1">
<constructor-arg ref="address1"></constructor-arg>
</bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and calls the
show method.
package com.javaknowledge;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e1=(Employee)factory.getBean("e2");
e1.show();
}
}
Dependency Injection by setter method
• We can inject the dependency by setter method also.
The <property>subelement of <bean> is used for
setter injection. Here we are going to inject
– primitive and String-based values
– Dependent object (contained object)
– Collection values etc.
• Injecting primitive and string-based values by setter
method
• Let's see the simple example to inject primitive and
string-based values by setter method. We have created
three files here:
– Employee.java (same as CI)
– applicationContext.xml
– Test.java (same as CI)
applicationContext.xml
• We are providing the information into the bean by this file. The property element invokes the setter method. The
value subelement of property will assign the specified value.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="obj" class="com.javaknowledge.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Abir</value>
</property>
<property name="city">
<value>Dhaka</value>
</property>
</bean>
</beans>
Difference between constructor and
setter injection
• There are many key differences between constructor
injection and setter injection.
– Partial dependency: can be injected using setter injection
but it is not possible by constructor. Suppose there are 3
properties in a class, having 3 arg constructor and setters
methods. In such case, if you want to pass information for
only one property, it is possible by setter method only.
– Overriding: Setter injection overrides the constructor
injection. If we use both constructor and setter injection,
IOC container will use the setter injection.
– Changes: We can easily change the value by setter
injection. It doesn't create a new bean instance always like
constructor. So setter injection is flexible than constructor
injection.
Autowiring in Spring
• Autowiring feature of spring framework enables
you to inject the object dependency implicitly. It
internally uses setter or constructor injection.
• Autowiring can't be used to inject primitive and
string values. It works with reference only.
• Advantage of Autowiring
– It requires the less code because we don't need to
write the code to inject the dependency explicitly.
• Disadvantage of Autowiring
– No control of programmer.
– It can't be used for primitive and string values.
Autowiring Modes
• There are many autowiring modes:
No. Mode Description
1) no It is the default autowiring mode. It means no autowiring
bydefault.
2) byName The byName mode injects the object dependency according
to name of the bean. In such case, property name and
bean name must be same. It internally calls setter method.
3) byType The byType mode injects the object dependency according
to type. So property name and bean name can be different.
It internally calls setter method.
4) constructor The constructor mode injects the dependency by calling the
constructor of the class. It calls the constructor having
large number of parameters.
5) autodetect It is deprecated since Spring 3.
Example of Autowiring
• Let's see the simple code to use autowiring in spring. You need to use
autowire attribute of bean element to apply the autowire modes.
• <bean id="a" class="org.sssit.A" autowire="byName"></bean>
• Let's see the full example of autowiring in spring. To create this example,
we have created 4 files.
– B.java
– A.java
– applicationContext.xml
– Test.java
• B.java
• This class contains a constructor and method only.
package org.sssit;
public class B {
B(){System.out.println("b is created");}
void print(){System.out.println("hello b");}
}
A.java
• This class contains reference of B class and constructor and method.
package org.sssit;
public class A {
B b;
A(){System.out.println("a is created");}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
void print(){System.out.println("hello a");}
void display(){
print();
b.print();
}
}
applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema
/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and calls the display
method.
package org.sssit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
A a=context.getBean("a",A.class);
a.display();
}
}
• Output:
– b is created
– a is created
– hello a
– hello b
1) byName autowiring mode
• In case of byName autowiring mode, bean id and
reference name must be same.
• It internally uses setter injection.
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
• But, if you change the name of bean, it will not
inject the dependency.
• Let's see the code where we are changing the
name of the bean from b to b1.
<bean id="b1" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
2) byType autowiring mode
• In case of byType autowiring mode, bean id and reference name
may be different. But there must be only one bean of a type.
• It internally uses setter injection.
<bean id="b1" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byType"></bean>
• In this case, it works fine because you have created an instance of B
type. It doesn't matter that you have different bean name than
reference name.
• But, if you have multiple bean of one type, it will not work and
throw exception.
• Let's see the code where are many bean of type B.
<bean id="b1" class="org.sssit.B"></bean>
<bean id="b2" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
• In such case, it will throw exception.
3) constructor autowiring mode
• In case of constructor autowiring mode, spring
container injects the dependency by highest
parameterized constructor.
• If you have 3 constructors in a class, zero-arg,
one-arg and two-arg then injection will be
performed by calling the two-arg constructor.
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="constructor"></bean>
4) no autowiring mode
• In case of no autowiring mode, spring
container doesn't inject the dependency by
autowiring.
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="no"></bean>
Dependency Injection with Factory Method
in Spring
• Spring framework provides facility to inject bean using factory method. To
do so, we can use two attributes of bean element.
– factory-method: represents the factory method that will be invoked to
inject the bean.
– factory-bean: represents the reference of the bean by which factory
method will be invoked. It is used if factory method is non-static.
• A method that returns instance of a class is called factory method.
public class A {
public static A getA(){//factory method
return new A();
}
}
Factory Method Types
• There can be three types of factory method:
• 1) A static factory method that returns instance of its own class. It
is used in singleton design pattern.
<bean id="a" class="com.javaknowledge.A" factory-
method="getA"></bean>
• 2) A static factory method that returns instance of another class. It
is used instance is not known and decided at runtime.
<bean id="b" class="com.javaknowledge.A" factory-
method="getB"></bean>
• 3) A non-static factory method that returns instance
of another class. It is used instance is not known and decided at
runtime.
<bean id="a" class="com.javaknowledge.A"></bean>
<bean id="b" class="com.javaknowledge.A" factory-
method="getB" factory-bean="a"></bean>
Type 1
• Let's see the simple code to inject the
dependency by static factory method.
<bean id="a" class="com.javaknowledge.A" factory-
method="getA"></bean>
• Let's see the full example to inject dependency
using factory method in spring. To create this
example, we have created 3 files.
– A.java
– applicationContext.xml
– Test.java
A.java
• This class is a singleton class.
package com.javaknowledge;
public class A {
private static final A obj=new A();
private A(){System.out.println("private constructor");}
public static A getA(){
System.out.println("factory method ");
return obj;
}
public void msg(){
System.out.println("hello user");
}
}
applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema
/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<bean id="a" class="com.javaknowledge.A" factory-
method="getA"></bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and calls the
msg method.
package com.javaknowledge;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("application
Context.xml");
A a=(A)context.getBean("a");
a.msg();
}
}
• Output:
– private constructor
– factory method
– hello user
Type 2
• Let's see the simple code to inject the dependency by static factory
method that returns the instance of another class.
• To create this example, we have created 6 files.
– Printable.java
– A.java
– B.java
– PrintableFactory.java
– applicationContext.xml
– Test.java
• Printable.java
package com.javknowledge;
public interface Printable {
void print();
}
A.java
package com.javaknowledge;
public class A implements Printable{
@Override
public void print() {
System.out.println("hello a");
}
}
• B.java
package com.javaknowledge;
public class B implements Printable{
@Override
public void print() {
System.out.println("hello b");
}
}
PrintableFactory.java
package com.javaknowledge;
public class PrintableFactory {
public static Printable getPrintable(){
//return new B();
return new A();//return any one instance, eith
er A or B
}
}
applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema
/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<bean id="p" class="com.javaknowledge.PrintableFactory" factory-
method="getPrintable"></bean>
</beans>
Test.java
• This class gets the bean from the applicationContext.xml file and
calls the print() method.
package com.javaknowledge;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationCo
ntext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("app
licationContext.xml");
Printable p=(Printable)context.getBean("p");
p.print();
}
}
• Output:
– hello a
Type 3
• Let's see the example to inject the dependency by non-
static factory method that returns the instance of
another class.
• To create this example, we have created 6 files.
– Printable.java
– A.java
– B.java
– PrintableFactory.java
– applicationContext.xml
– Test.java
• All files are same as previous, you need to change only
2 files: PrintableFactory and applicationContext.xml.
PrintableFactory.java
package com.javaknowledge;
public class PrintableFactory {
//non-static factory method
public Printable getPrintable(){
return new A();//return any one instance, either A
or B
}
}
applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="pfactory" class="com.javaknowledge.PrintableFactory"></bean>
<bean id="p" class="com.javaknowledge.PrintableFactory" factory-
method="getPrintable"
factory-bean="pfactory"></bean>
</beans>
• Output:
– hello a

Dependency Injection in Spring

  • 2.
    Dependency Injection inSpring • Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled. • Let's write a code without following IOC and DI.
  • 3.
    Dependency Injection inSpring class Restaurant{ Tea tea = new Tea(); //creating instance public void prepareDrink(){ tea.prepareTea(); } } class Tea{ public void prepareTea(){ // prepare tea } } • Here you can see, there is dependency between Restaurant and Tea classes. That means if you need to change the constructor of Tea class at any point you need to change the object of Tea in Restaurant class too. • Now see the following example with slide modification.
  • 4.
    Dependency Injection inSpring In this case we are not using tea object directly in Restaurant class and thus they are loosely coupled. This is just an example of loosely coupled design pattern. Spring framework use this pattern by constructor or setter method which we can be configured in a configuration file provided by spring. class Restaurant{ Drink drink; Restaurant(Drink drink){ this.drink = drink; } //Tea tea = new Tea(); //no need to create this instance public void prepareDrink(){ drink.prepareTea(); } } interface Drink{ public void prepareTea(); } class Tea implements Drink{ public void prepareTea(){ // prepare tea } }
  • 5.
    Two ways toperform Dependency Injection in Spring framework • Spring framework provides two ways to inject dependency – By Constructor – By Setter method
  • 6.
    Dependency Injection byConstructor Example • We can inject the dependency by constructor. The <constructor-arg>subelement of <bean> is used for constructor injection. Here we are going to inject – primitive and String-based values – Dependent object (contained object) – Collection values etc.
  • 7.
    Injecting primitive andstring-based values • Let's see the simple example to inject primitive and string-based values. We have created three files here: – Employee.java – applicationContext.xml – Test.java
  • 8.
    Employee.java It is asimple class containing two fields id and name. There are four constructors and one method in this class. package com.javaknowledge; public class Employee { private int id; private String name; public Employee() {System.out.println("def cons");} public Employee(int id) {this.id = id;} public Employee(String name) { this.name = name;} public Employee(int id, String name) { this.id = id; this.name = name; } void show(){ System.out.println(id+" "+name); } }
  • 9.
    applicationContext.xml • We areproviding the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value. The type attribute specifies that int parameter constructor will be invoked. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="e" class=" com.javaknowledge.Employee"> <constructor-arg value="10" type="int"></constructor-arg> </bean> </beans>
  • 10.
    Test.java • Test.javaThis classgets the bean from the applicationContext.xml file and calls the show method. package com.javaknowledge; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.*; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Employee s=(Employee)factory.getBean("e"); s.show(); } } • Output:10 null
  • 11.
    Injecting string-based values •If you don't specify the type attribute in the constructor-arg element, by default string type constructor will be invoked. • You may pass integer literal and string both as following.... <bean id="e" class="com.javaknowledge.Employee"> <constructor-arg value="10" type="int" ></constructor-arg> <constructor-arg value=“Bari"></constructor-arg> </bean> • Output:10 Bari
  • 12.
    Constructor Injection withDependent Object • If there is HAS-A relationship between the classes, we create the instance of dependent object (contained object) first then pass it as an argument of the main class constructor. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object. Let's see the Address class first:
  • 13.
    Address.java • This classcontains three properties, one constructor and toString() method to return the values of these object. package com.javaknowledge; public class Address { private String city; private String state; private String country; public Address(String city, String state, String country) { super(); this.city = city; this.state = state; this.country = country; } public String toString(){ return city+" "+state+" "+country; } }
  • 14.
    Employee.java • It containsthree properties id, name and address(dependent object) ,two constructors and show() method to show the records of the current object including the depedent object. package com.javaknowledge; public class Employee { private int id; private String name; private Address address;//Aggregation public Employee() {System.out.println("def cons");} public Employee(int id, String name, Address address) { super(); this.id = id; this.name = name; this.address = address; } void show(){ System.out.println(id+" "+name); System.out.println(address.toString()); } }
  • 15.
    applicationContext.xml • The refattribute is used to define the reference of another object, such way we are passing the dependent object as an constructor argument. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans- 3.0.xsd"> <bean id="a1" class=" com.javaknowledge.Address"> <constructor-arg value=“Kakrile"></constructor-arg> <constructor-arg value=“Dhaka"></constructor-arg> <constructor-arg value=“Bangladesh"></constructor-arg> </bean> ....
  • 16.
    <bean id="e" class="com.javaknowledge.Employee"> <constructor-argvalue="12" type="int"></constructor-arg> <constructor-arg value=“Bari"></constructor-arg> <constructor-arg> <ref bean="a1"/> </constructor-arg> </bean> </beans>
  • 17.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the show method. package com.javaknowledge; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.*; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Employee s=(Employee)factory.getBean("e"); s.show(); } }
  • 18.
    Constructor Injection withCollection Example • We can inject collection values by constructor in spring framework. There can be used three elements inside the constructor-arg element. • It can be: – list – set – map • Each collection can have the applicationContext.xml file and List to Set in the Question.java file. string based and non-string based values. In this example, we are taking the example of Forum where One question can have multiple answers. There are three pages: – Question.java – applicationContext.xml – Test.java • In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in
  • 19.
    Question.java • This classcontains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers. package com.javaknowledge; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List<String> answers; public Question() {} public Question(int id, String name, List<String> answers) { super(); this.id = id; this.name = name; this.answers = answers; } public void displayInfo(){ System.out.println(id+" "+name); System.out.println("answers are:"); Iterator<String> itr=answers.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 20.
    applicationContext.xml • The listelement of constructor-arg is used here to define the list. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="q" class="com.javaknowledge.Question"> <constructor-arg value="111"></constructor-arg> <constructor-arg value="What is java?"></constructor-arg> <constructor-arg> <list> <value>Java is a programming language</value> <value>Java is a Platform</value> <value>Java is an Island of Indonasia</value> </list> </constructor-arg> </bean> </beans>
  • 21.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the displayInfo method. package com.javaknowledge; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Question q=(Question)factory.getBean("q"); q.displayInfo(); } }
  • 22.
    Constructor Injection withNon-String Collection (having Dependent Object) Example • If we have dependent object in the collection, we can inject these information by using the ref element inside the list, set or map. • In this example, we are taking the example of Forum where One question can have multiple answers. But Answer has its own information such as answerId, answer and postedBy. There are four pages used in this example: – Question.java – Answer.java – applicationContext.xml – Test.java • In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
  • 23.
    Question.java • This classcontains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers. package com.javaknowledge; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List<Answer> answers; public Question() {} public Question(int id, String name, List<Answer> answers) { super(); this.id = id; this.name = name; this.answers = answers; } public void displayInfo(){ System.out.println(id+" "+name); System.out.println("answers are:"); Iterator<Answer> itr=answers.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 24.
    Answer.java • This classhas three properties id, name and by with constructor and toString() method. package com.javaknowledge; public class Answer { private int id; private String name; private String by; public Answer() {} public Answer(int id, String name, String by) { super(); this.id = id; this.name = name; this.by = by; } public String toString(){ return id+" "+name+" "+by; } }
  • 25.
    applicationContext.xml • The refelement is used to define the reference of another bean. Here, we are using bean attribute of ref element to specify the reference of another bean. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="ans1" class=" com.javaknowledge.Answer"> <constructor-arg value="1"></constructor-arg> <constructor-arg value="Java is a programming language"></constructor-arg> <constructor-arg value="John"></constructor-arg> </bean> <bean id="ans2" class=" com.javaknowledge.Answer"> <constructor-arg value="2"></constructor-arg> <constructor-arg value="Java is a Platform"></constructor-arg> <constructor-arg value="Raji"></constructor-arg> </bean> <bean id="q" class=" com.javaknowledge.Question"> <constructor-arg value="111"></constructor-arg> <constructor-arg value="What is java?"></constructor-arg> <constructor-arg> <list> <ref bean="ans1"/> <ref bean="ans2"/> </list> </constructor-arg> </bean> </beans>
  • 26.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the displayInfo method. package com.javaknowledge; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Question q=(Question)factory.getBean("q"); q.displayInfo(); } }
  • 27.
    Inheriting Bean inSpring • By using the parent attribute of bean, we can specify the inheritance relation between the beans. In such case, parent bean values will be inherited to the current bean. • Let's see the simple example to inherit the bean.
  • 28.
    Employee.java • This classcontains three properties, three constructor and show() method to display the values. package com.javaknowledge; public class Employee { private int id; private String name; private Address address; public Employee() {} public Employee(int id, String name) { super(); this.id = id; this.name = name; } public Employee(int id, String name, Address address) { super(); this.id = id; this.name = name; this.address = address; } void show(){ System.out.println(id+" "+name); System.out.println(address); } }
  • 29.
    Address.java package com.javaknowledge; public classAddress { private String addressLine1,city,state,country; public Address(String addressLine1, String city, String state, String country) { super(); this.addressLine1 = addressLine1; this.city = city; this.state = state; this.country = country; } public String toString(){ return addressLine1+" "+city+" "+state+" "+country; } }
  • 30.
    applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <beanid="e1" class="com.javaknowledge.Employee"> <constructor-arg value="101"></constructor-arg> <constructor-arg value=“A"></constructor-arg> </bean> <bean id="address1" class="com. javaknowledge.Address"> <constructor-arg value="21,Shantinagar"></constructor-arg> <constructor-arg value=“Dhaka"></constructor-arg> <constructor-arg value=“Dhaka"></constructor-arg> <constructor-arg value=“Bangladesh"></constructor-arg> </bean> <bean id="e2" class="com. javaknowledge.Employee" parent="e1"> <constructor-arg ref="address1"></constructor-arg> </bean> </beans>
  • 31.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the show method. package com.javaknowledge; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Employee e1=(Employee)factory.getBean("e2"); e1.show(); } }
  • 32.
    Dependency Injection bysetter method • We can inject the dependency by setter method also. The <property>subelement of <bean> is used for setter injection. Here we are going to inject – primitive and String-based values – Dependent object (contained object) – Collection values etc. • Injecting primitive and string-based values by setter method • Let's see the simple example to inject primitive and string-based values by setter method. We have created three files here: – Employee.java (same as CI) – applicationContext.xml – Test.java (same as CI)
  • 33.
    applicationContext.xml • We areproviding the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="obj" class="com.javaknowledge.Employee"> <property name="id"> <value>20</value> </property> <property name="name"> <value>Abir</value> </property> <property name="city"> <value>Dhaka</value> </property> </bean> </beans>
  • 34.
    Difference between constructorand setter injection • There are many key differences between constructor injection and setter injection. – Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only. – Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection. – Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor. So setter injection is flexible than constructor injection.
  • 35.
    Autowiring in Spring •Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection. • Autowiring can't be used to inject primitive and string values. It works with reference only. • Advantage of Autowiring – It requires the less code because we don't need to write the code to inject the dependency explicitly. • Disadvantage of Autowiring – No control of programmer. – It can't be used for primitive and string values.
  • 36.
    Autowiring Modes • Thereare many autowiring modes: No. Mode Description 1) no It is the default autowiring mode. It means no autowiring bydefault. 2) byName The byName mode injects the object dependency according to name of the bean. In such case, property name and bean name must be same. It internally calls setter method. 3) byType The byType mode injects the object dependency according to type. So property name and bean name can be different. It internally calls setter method. 4) constructor The constructor mode injects the dependency by calling the constructor of the class. It calls the constructor having large number of parameters. 5) autodetect It is deprecated since Spring 3.
  • 37.
    Example of Autowiring •Let's see the simple code to use autowiring in spring. You need to use autowire attribute of bean element to apply the autowire modes. • <bean id="a" class="org.sssit.A" autowire="byName"></bean> • Let's see the full example of autowiring in spring. To create this example, we have created 4 files. – B.java – A.java – applicationContext.xml – Test.java • B.java • This class contains a constructor and method only. package org.sssit; public class B { B(){System.out.println("b is created");} void print(){System.out.println("hello b");} }
  • 38.
    A.java • This classcontains reference of B class and constructor and method. package org.sssit; public class A { B b; A(){System.out.println("a is created");} public B getB() { return b; } public void setB(B b) { this.b = b; } void print(){System.out.println("hello a");} void display(){ print(); b.print(); } }
  • 39.
  • 40.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the display method. package org.sssit; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); A a=context.getBean("a",A.class); a.display(); } } • Output: – b is created – a is created – hello a – hello b
  • 41.
    1) byName autowiringmode • In case of byName autowiring mode, bean id and reference name must be same. • It internally uses setter injection. <bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean> • But, if you change the name of bean, it will not inject the dependency. • Let's see the code where we are changing the name of the bean from b to b1. <bean id="b1" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean>
  • 42.
    2) byType autowiringmode • In case of byType autowiring mode, bean id and reference name may be different. But there must be only one bean of a type. • It internally uses setter injection. <bean id="b1" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byType"></bean> • In this case, it works fine because you have created an instance of B type. It doesn't matter that you have different bean name than reference name. • But, if you have multiple bean of one type, it will not work and throw exception. • Let's see the code where are many bean of type B. <bean id="b1" class="org.sssit.B"></bean> <bean id="b2" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean> • In such case, it will throw exception.
  • 43.
    3) constructor autowiringmode • In case of constructor autowiring mode, spring container injects the dependency by highest parameterized constructor. • If you have 3 constructors in a class, zero-arg, one-arg and two-arg then injection will be performed by calling the two-arg constructor. <bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="constructor"></bean>
  • 44.
    4) no autowiringmode • In case of no autowiring mode, spring container doesn't inject the dependency by autowiring. <bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="no"></bean>
  • 45.
    Dependency Injection withFactory Method in Spring • Spring framework provides facility to inject bean using factory method. To do so, we can use two attributes of bean element. – factory-method: represents the factory method that will be invoked to inject the bean. – factory-bean: represents the reference of the bean by which factory method will be invoked. It is used if factory method is non-static. • A method that returns instance of a class is called factory method. public class A { public static A getA(){//factory method return new A(); } }
  • 46.
    Factory Method Types •There can be three types of factory method: • 1) A static factory method that returns instance of its own class. It is used in singleton design pattern. <bean id="a" class="com.javaknowledge.A" factory- method="getA"></bean> • 2) A static factory method that returns instance of another class. It is used instance is not known and decided at runtime. <bean id="b" class="com.javaknowledge.A" factory- method="getB"></bean> • 3) A non-static factory method that returns instance of another class. It is used instance is not known and decided at runtime. <bean id="a" class="com.javaknowledge.A"></bean> <bean id="b" class="com.javaknowledge.A" factory- method="getB" factory-bean="a"></bean>
  • 47.
    Type 1 • Let'ssee the simple code to inject the dependency by static factory method. <bean id="a" class="com.javaknowledge.A" factory- method="getA"></bean> • Let's see the full example to inject dependency using factory method in spring. To create this example, we have created 3 files. – A.java – applicationContext.xml – Test.java
  • 48.
    A.java • This classis a singleton class. package com.javaknowledge; public class A { private static final A obj=new A(); private A(){System.out.println("private constructor");} public static A getA(){ System.out.println("factory method "); return obj; } public void msg(){ System.out.println("hello user"); } }
  • 49.
  • 50.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the msg method. package com.javaknowledge; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("application Context.xml"); A a=(A)context.getBean("a"); a.msg(); } } • Output: – private constructor – factory method – hello user
  • 51.
    Type 2 • Let'ssee the simple code to inject the dependency by static factory method that returns the instance of another class. • To create this example, we have created 6 files. – Printable.java – A.java – B.java – PrintableFactory.java – applicationContext.xml – Test.java • Printable.java package com.javknowledge; public interface Printable { void print(); }
  • 52.
    A.java package com.javaknowledge; public classA implements Printable{ @Override public void print() { System.out.println("hello a"); } } • B.java package com.javaknowledge; public class B implements Printable{ @Override public void print() { System.out.println("hello b"); } }
  • 53.
    PrintableFactory.java package com.javaknowledge; public classPrintableFactory { public static Printable getPrintable(){ //return new B(); return new A();//return any one instance, eith er A or B } }
  • 54.
  • 55.
    Test.java • This classgets the bean from the applicationContext.xml file and calls the print() method. package com.javaknowledge; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationCo ntext; public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("app licationContext.xml"); Printable p=(Printable)context.getBean("p"); p.print(); } } • Output: – hello a
  • 56.
    Type 3 • Let'ssee the example to inject the dependency by non- static factory method that returns the instance of another class. • To create this example, we have created 6 files. – Printable.java – A.java – B.java – PrintableFactory.java – applicationContext.xml – Test.java • All files are same as previous, you need to change only 2 files: PrintableFactory and applicationContext.xml.
  • 57.
    PrintableFactory.java package com.javaknowledge; public classPrintableFactory { //non-static factory method public Printable getPrintable(){ return new A();//return any one instance, either A or B } }
  • 58.