0% found this document useful (0 votes)
1 views24 pages

Unit 5 Spring Framework in Java

The Spring Framework is a lightweight framework that supports various other frameworks and is structured into several modules including IOC, AOP, and MVC. It utilizes design patterns like Inversion of Control (IOC) and Dependency Injection (DI) to promote loose coupling, making code easier to maintain and test. The framework provides predefined templates, is non-invasive, and offers powerful abstractions for JavaEE specifications, facilitating fast development and declarative support for various functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views24 pages

Unit 5 Spring Framework in Java

The Spring Framework is a lightweight framework that supports various other frameworks and is structured into several modules including IOC, AOP, and MVC. It utilizes design patterns like Inversion of Control (IOC) and Dependency Injection (DI) to promote loose coupling, making code easier to maintain and test. The framework provides predefined templates, is non-invasive, and offers powerful abstractions for JavaEE specifications, facilitating fast development and declarative support for various functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Spring Framework

Spring is a lightweight framework. It can be thought of as a framework of


frameworks because it provides support to various frameworks such
as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework, in broader sense, can be
defined as a structure where we find solution of the various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context,
ORM, WEB MVC etc.

Inversion Of Control (IOC) and Dependency


Injection
These are the design patterns that are used to remove dependency from the
programming code. They make the code easier to test and maintain.

class Employee{

1. Address address;
2. Employee(){
3. address=new Address();
4. }
5. }

In such case, there is dependency between the Employee and Address (tight
coupling). In the Inversion of Control scenario, we do this something like this:

1. class Employee{
2. Address address;
3. Employee(Address address){
4. this.address=address;
5. }
6. }

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify
the code if our logic is moved to new environment.

In Spring framework, IOC container is responsible to inject the dependency. We


provide metadata to the IOC container either by XML file or annotation.
Advantage of Dependency Injection

o makes the code loosely coupled so easy to maintain


o makes the code easy to test

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:

1) Predefined Templates

Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So
there is no need to write too much code. It hides the basic steps of these
technologies.

2) Loose Coupling

The Spring applications are loosely coupled because of dependency injection.

3) Easy to test

The Dependency Injection makes easier to test the application. The EJB or Struts
application require server to run the application but Spring framework doesn't
require server.

4) Lightweight

Spring framework is lightweight because of its POJO implementation. The Spring


Framework doesn't force the programmer to inherit any class or implement any
interface. That is why it is said non-invasive.

5) Fast Development

The Dependency Injection feature of Spring Framework and it support to various


frameworks makes the easy development of JavaEE application.

6) Powerful abstraction

It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and
JTA.

7) Declarative support

It provides declarative support for caching, validation, transactions and formatting.


Spring Modules
The Spring framework comprises of many modules such as core, beans, context,
expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS,
Transaction, Web, Servlet, Struts etc. These modules are grouped into Test, Core
Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC /
Remoting) as displayed in the following diagram.
Spring Example
o create the class
o create the xml file to provide the values
o create the test class
o Load the spring jar files
o Run the test class

) Create Java class


This is the simple java bean class containing the name property only.

1. package com.ucer;
2.
3. public class Student {
4. private String name;
5.
6. public String getName() {
7. return name;
8. }
9.
10. public void setName(String name) {
11. this.name = name;
12. }
13.
14. public void displayInfo(){
15. System.out.println("Hello: "+name);
16. }
17. }
2) Create the xml file
In case of myeclipse IDE, you don't need to create the xml file as myeclipse does this
for yourselves. Open the applicationContext.xml file, and write the following code:

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
8.
9. <bean id="studentbean" class="com.ucer.Student">
10. <property name="name" value="Vimal Jaiswal"></property>
11. </bean>
12.
13. </beans>

3) Create the test class


Create the java class e.g. Test. Here we are getting the object of Student class from
the IOC container using the getBean() method of BeanFactory

1. package com.ucer;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource resource=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(resource);
12.
13. Student student=(Student)factory.getBean("studentbean");
14. student.displayInfo();
15. }
16. }

4) Load the jar files required for spring framework


There are mainly three jar files required to run this application.

o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A

IoC Container
The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC container gets informations from the XML file and works accordingly. The
main tasks performed by IoC container are:

o to instantiate the application class


o to configure the object
o to assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext

Difference between BeanFactory and the


ApplicationContext
The org.springframework.beans.factory.BeanFactory and the
org.springframework.context.ApplicationContext interfaces acts as the IoC
container. The ApplicationContext interface is built on top of the BeanFactory
interface. It adds some extra functionality than BeanFactory such as simple
integration with Spring's AOP, message resource handling (for I18N), event
propagation, application layer specific context (e.g. WebApplicationContext) for web
application. So it is better to use ApplicationContext than BeanFactory.

Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To use
the BeanFactory, we need to create the instance of XmlBeanFactory class as given
below:

1. Resource resource=new ClassPathResource("applicationContext.xml");


2. BeanFactory factory=new XmlBeanFactory(resource);

The constructor of XmlBeanFactory class receives the Resource object so we need to


pass the resource object to create the object of BeanFactory.

Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of
ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as given below:

1. ApplicationContext context =
2. new ClassPathXmlApplicationContext("applicationContext.xml");

The constructor of ClassPathXmlApplicationContext class receives string, so we can pass the


name of the xml file to create the instance of ApplicationContext.
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. To understand
the DI better,

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.

o tight coupling The dependency lookup approach makes the code tightly
coupled. If resource is changed, we need to perform a lot of modification in
the code.
o Not easy for testing This approach creates a lot of problems while testing the
application especially in black box testing.

Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the
programs. In such case we provide the information from the external source such as
XML file. It makes our code loosely coupled and easier for testing. In such case we
write the code as:

1. class Employee{
2. Address address;
3.
4. Employee(Address address){
5. this.address=address;
6. }
7. public void setAddress(Address address){
8. this.address=address;
9. }
10.
11. }

In such case, instance of Address class is provided by external souce such as XML file
either by constructor or setter method.
Two ways to perform Dependency Injection in Spring
framework

o By Constructor
o By Setter method

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

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values by setter


method

o Employee.java
o applicationContext.xml
o Test.java

1. package com.ucer;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private String city;
7.
8. public int getId() {
9. return id;
10. }
11. public void setId(int id) {
12. this.id = id;
13. }
14. public String getName() {
15. return name;
16. }
17. public void setName(String name) {
18. this.name = name;
19. }
20.
21. public String getCity() {
22. return city;
23. }
24. public void setCity(String city) {
25. this.city = city;
26. }
27. void display(){
28. System.out.println(id+" "+name+" "+city);
29. }
30.
31. }

applicationContext.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
8.
9. <bean id="obj" class="com.ucer.Employee">
10. <property name="id">
11. <value>101</value>
12. </property>
13. <property name="name">
14. <value>Shashi</value>
15. </property>
16. <property name="city">
17. <value>Prayagraj</value>
18. </property>
19.
20. </bean>
21.
22. </beans>

Test.java

1. package com.ucer;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee e=(Employee)factory.getBean("obj");
14. s.display();
15.
16. }
17. }

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

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values

o Employee.java
o applicationContext.xml
o Test.java

Employee.java

1. package com.ucer;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. public Employee() {System.out.println("def cons");}
8.
9. public Employee(int id) {this.id = id;}
10.
11. public Employee(String name) { this.name = name;}
12.
13. public Employee(int id, String name) {
14. this.id = id;
15. this.name = name;
16. }
17.
18. void show(){
19. System.out.println(id+" "+name);
20. }
21.
22. }

applicationContext.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
8.
9. <bean id="e" class="com.ucer.Employee">
10. <constructor-arg value="10" type="int"></constructor-arg>
11. <constructor-arg value="Shashi" type="String"></constructor-arg>
12.
13. </bean>
14.
15. </beans>

Test.java

1. package com.ucer;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)factory.getBean("e");
14. s.show();
15.
16. }
17. }
Constructor Injection with Dependent
Object
Address.java

1. package com.ucer;
2.
3. public class Address {
4. private String city;
5. private String state;
6. private String country;
7.
8. public Address(String city, String state, String country) {
9. super();
10. this.city = city;
11. this.state = state;
12. this.country = country;
13. }
14.
15. public String toString(){
16. return city+" "+state+" "+country;
17. }
18. }
Employee.java

1. package com.ucer;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private Address address;//Aggregation
7.
8. public Employee() {System.out.println("def cons");}
9.
10. public Employee(int id, String name, Address address) {
11. super();
12. this.id = id;
13. this.name = name;
14. this.address = address;
15. }
16.
17. void show(){
18. System.out.println(id+" "+name);
19. System.out.println(address.toString());
20. }
21.
22. }

Spring.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
8.
9. <bean id="a1" class="com.ucer.Address">
10. <constructor-arg value="Gzb"></constructor-arg>
11. <constructor-arg value="UP"></constructor-arg>
12. <constructor-arg value="India"></constructor-arg>
13. </bean>
14.
15.
16. <bean id="e" class="com.ucer.Employee">
17. <constructor-arg value="12" type="int"></constructor-arg>
18. <constructor-arg value="shashi" type="String"></constructor-arg>
19. <constructor-arg> <ref bean="a1"/> </constructor-arg>
20. </bean>
21.
22. </beans>

Test.java

1. package com.ucer;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("spring.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)factory.getBean("e");
14. s.show();
15.
16. }
17. }

Constructor Injection with Non-String


Collection (having Dependent Object)
Example
Question.java

1. package com.ucer;
2.
3. import java.util.Iterator;
4. import java.util.List;
5.
6. public class Question {
7. private int id;
8. private String name;
9. private List<Answer> answers;
10.
11. public Question() {}
12. public Question(int id, String name, List<Answer> answers) {
13. super();
14. this.id = id;
15. this.name = name;
16. this.answers = answers;
17. }
18.
19. public void displayInfo(){
20. System.out.println(id+" "+name);
21. System.out.println("answers are:");
22. Iterator<Answer> itr=answers.iterator();
23. while(itr.hasNext()){
24. System.out.println(itr.next());
25. }
26. }
27.
28. }

Answer.java

1. package com.ucer;
2.
3. public class Answer {
4. private int id;
5. private String name;
6. private String by;
7.
8. public Answer() {}
9. public Answer(int id, String name, String by) {
10. super();
11. this.id = id;
12. this.name = name;
13. this.by = by;
14. }
15.
16. public String toString(){
17. return id+" "+name+" "+by;
18. }
19. }

applicationContext.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="ans1" class="com.ucer.Answer">
10. <constructor-arg value="1"></constructor-arg>
11. <constructor-arg value="Java is a programming language"></constructor-
arg>
12. <constructor-arg value="John"></constructor-arg>
13. </bean>
14.
15. <bean id="ans2" class="com.ucer.Answer">
16. <constructor-arg value="2"></constructor-arg>
17. <constructor-arg value="Java is a Platform"></constructor-arg>
18. <constructor-arg value="Ravi"></constructor-arg>
19. </bean>
20.
21. <bean id="q" class="com.ucer.Question">
22. <constructor-arg value="111"></constructor-arg>
23. <constructor-arg value="What is java?"></constructor-arg>
24. <constructor-arg>
25. <list>
26. <ref bean="ans1"/>
27. <ref bean="ans2"/>
28. </list>
29. </constructor-arg>
30. </bean>
31.
32. </beans>
Test.java

1. package com.ucer;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Question q=(Question)factory.getBean("q");
14. q.displayInfo();
15.
16. }
17. }

Constructor Injection with Map Example


Question.java

1. package com.ucer;
2. import java.util.Iterator;
3. import java.util.Map;
4. import java.util.Set;
5. import java.util.Map.Entry;
6.
7. public class Question {
8. private int id;
9. private String name;
10. private Map<String,String> answers;
11.
12. public Question() {}
13. public Question(int id, String name, Map<String, String> answers) {
14. super();
15. this.id = id;
16. this.name = name;
17. this.answers = answers;
18. }
19.
20. public void displayInfo(){
21. System.out.println("question id:"+id);
22. System.out.println("question name:"+name);
23. System.out.println("Answers....");
24. Set<Entry<String, String>> set=answers.entrySet();
25. Iterator<Entry<String, String>> itr=set.iterator();
26. while(itr.hasNext()){
27. Entry<String,String> entry=itr.next();
28. System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValu
e());
29. }
30. }
31. }
applicationContext.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="q" class="com.ucer.Question">
10. <constructor-arg value="11"></constructor-arg>
11. <constructor-arg value="What is Java?"></constructor-arg>
12. <constructor-arg>
13. <map>
14. <entry key="Java is a Programming Language" value="shashi"></entry>
15. <entry key="Java is a Platform" value="John Smith"></entry>
16. <entry key="Java is an Island" value="Raj"></entry>
17. </map>
18. </constructor-arg>
19. </bean>
20.
21. </beans>
Test.java

1. package com.ucer;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Question q=(Question)factory.getBean("q");
14. q.displayInfo();
15.
16. }
17. }
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
B.java

1. package org.ucer;
2. public class B {
3. B(){System.out.println("b is created");}
4. void print(){System.out.println("hello b");}
5. }
A.java

1. package org.ucer;
2. public class A {
3. B b;
4. A(){System.out.println("a is created");}
5. public B getB() {
6. return b;
7. }
8. public void setB(B b) {
9. this.b = b;
10. }
11. void print(){System.out.println("hello a");}
12. void display(){
13. print();
14. b.print();
15. }
16. }

applicationContext.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="b" class="org.ucer.B"></bean>
10. <bean id="a" class="org.ucer.A" autowire="byName"></bean>
11.
12. </beans>
Test.java

1. package org.ucer;
2. import org.springframework.context.ApplicationContext;
3. import org.springframework.context.support.ClassPathXmlApplicationContext;

4. public class Test {


5. public static void main(String[] args) {
6. ApplicationContext context=new ClassPathXmlApplicationContext("applicat
ionContext.xml");
7. A a=context.getBean("a",A.class);
8. a.display();
9. }
10. }

Output:

b is created
a is created
hello a
hello b

You might also like