Unit-5 Spring Framework
Unit-5 Spring Framework
The Spring Framework is a powerful, lightweight, and widely used Java framework for building
enterprise applications. It provides a comprehensive programming and configuration model for Java-
based applications, making development faster, scalable, and maintainable.
Before Enterprise Java Beans (EJB), JavaBeans were used for developing Web applications, but they
lacked essential services like transaction management and security. EJB was introduced to address
this by offering services for enterprise application development. However, it was complex, requiring
developers to create Home and Remote interfaces and implement lifecycle methods.
1. Light weight:
Spring framework is light weight framework because of its POJO model implementation.
2. Non-invasive approach:
As we know that struts forces programmer to extend Action Class but spring framework
doesn’t force a programmer to extend class or implement interface given by Spring API.
3. Loose Coupling:
Because of dependency injection concept, spring objects are loosely coupled.
4. Modular fashion:
Spring framework is designed in modular fashion. A programmer can use only needed
modules and ignore the rest.
5. Easy Testing:
Dependency injection and POJO model makes easy to test an application.
6. Transaction management interface:
Spring framework provides transaction management interface for transaction management.
7. No need of application server:
Struts or EJB application require application server to run but spring application doesn’t need
an application server.
8. MVC framework:
Spring framework is a great alternative to web MVC frameworks like Struts.
1|Page
Spring Framework (Unit-5)
1. Test:
Spring test module provides the supports for testing of spring components with JUnit or TestNG
frameworks.
2. Core Container:
Spring core container contains the following:
a. Core: Core module provides the fundamental features of spring framework like IoC and DI.
b. Bean: Bean module provides the BeanFactory.
c. Context: Context module provides a way to access any object. ApplicationContext interface is the
main part of Context module.
d. Expression language: Expression language module provides a way to manipulate objects at runtime.
2|Page
Spring Framework (Unit-5)
etc.
c. OXM: OXM module provides an abstraction layer for Object/XML mapping APIs like JAXB, Castor
and XMLBeans etc.
d. JMS: JMS module provides feature of message processing.
e. Transaction: Transaction module provides the facility of transaction management for classes like
POJOs etc.
4. Web:
Web module consist of Web, Web-Servlet, Web-Struts, Web-Socket and Web-Portlet which provides
the facility of creating web applications.
5. AOP:
AOP module provides aspect-oriented programming implementation which provides the facility to
define method-interceptors.
6. Instrumentation:
Instrumentation module provides class instrumentation support and class loader implementations
BeanFactory:
BeanFactory org.springframework.beans.factory. BeanFactory is the interface and XmlBeanFactory is
an implementation class of it. It is a simple container which provides the basic support for dependency
injection.
ApplicationContext:
ApplicationContext org.springframework.context. ApplicationContext is the interface and
ClassPathXmlApplicationContext is an implementation class of it. ApplicationContext container
includes all functionality of the BeanFactory container with some extra functionality like
internationalization, event listeners etc.
3|Page
Spring Framework (Unit-5)
Spring bean
A spring bean represents an object that is created, configured and managed by spring container. A spring
bean is created by configuration metadata passed to the spring container which tells the container about
bean creation, bean lifecycle and bean dependencies.
4|Page
Spring Framework (Unit-5)
</bean>
</beans>
To define a prototype scope, you can set the scope property to prototype in the bean configuration file,
as shown in the following code snippet −
<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
5|Page
Spring Framework (Unit-5)
6|Page
Spring Framework (Unit-5)
Note:
1. We can also use ApplicationContext object for getting bean object as:
Synyax:
ApplicationContext context =
new ClassPathXmlApplicationContext("spring configuration file");
TestBean testBean = (TestBean) context.getBean("testBeanId");
2. Spring IOC container is responsible for creating bean objects and dependency injection.
3. Spring uses singleton design pattern for beans, so every spring bean is singleton class by default.
Example:
HelloWorld.java
package com.w3schools.business;
public class HelloWorld {
private String userName;
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
Test.java
package com.w3schools.business;
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");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.sayHello();
}
}
Output:
Hello: jai
Spring - Inversion of Control with Example
7|Page
Spring Framework (Unit-5)
Spring IoC (Inversion of Control) Container is the core of the Spring Framework. It creates objects
(beans), configures them, injects dependencies, and manages their life cycles. The container uses
Dependency Injection (DI) to manage application components. It retrieves object configuration from
XML files, Java-based configuration, annotations, or POJOs. Since the Spring IoC container, not the
developer, controls the object lifecycle and dependency management, this concept is called Inversion of
Control (IoC).
Spring - BeanFactory
Beans are Java objects that are configured at run-time by Spring IoC Container. BeanFactory represents
a basic IoC container which is a parent interface of ApplicationContext. BeanFactory uses Beans and
their dependencies metadata to create and configure them at run-time. BeanFactory loads the bean
definitions and dependency amongst the beans based on a configuration file (XML) or the beans can
be directly returned when required using Java Configuration. There are other types of configuration
files like LDAP, RDMS, properties files, etc. BeanFactory does not support Annotation-based
configuration whereas ApplicationContext does.
Some of the methods of Bean Factory before landing up on implementation which are shown below in
tabular format:
Method Description
containsBean(String name) Does this bean factory contain a bean definition or externally
registered singleton instance with the given name?
getBean(String name) Return an instance, which may be shared or independent, of the
specified bean.
getBean(String name, Class<T> Return an instance, which may be shared or independent, of the
requiredType) specified bean.
getBean(String name, Object... args) Return an instance, which may be shared or independent, of the
specified bean.
getType(String name) Determine the type of the bean with the given name.
isSingleton(String name) Is this bean a shared singleton? That is, will
getBean(java.lang.String) always return the same instance?
isTypeMatch(String name, Class<?> Check whether the bean with the given name matches the
typeToMatch) specified type.
Procedure:
First, create a Spring project using start.spring.io.
Create a POJO class.
Configure the Student bean in the bean-factory-demo.xml file.
Then write it to application class.
8|Page
Spring Framework (Unit-5)
Spring - ApplicationContext
ApplicationContext is the sub-interface of BeanFactory. It is used when we are creating an
enterprise-level application or web application. ApplicationContext is the superset of BeanFactory,
whatever features provided by BeanFactory are also provided by ApplicationContext.
ApplicationContext Features
ApplicationContext provides basic features in addition to enterprise-specific functionalities which are
as follows:
Publishing events to registered listeners by resolving property files.
Methods for accessing application components.
Supports Internationalization.
Loading File resources in a generic fashion.
9|Page
Spring Framework (Unit-5)
10 | P a g e
Spring Framework (Unit-5)
public Student() {
address = new Address();
}
}
11 | P a g e
Spring Framework (Unit-5)
In above example Student class requires an Address object and it is responsible for initializing and using
the Address object. If Address class constructor is changed in future then we have to make changes in
Student class also. This approach makes tight coupling between Student and Address objects. We can
resolve this problem using dependency injection design pattern. i.e. Address object will be implemented
independently and will be provided to Student when Student is instantiated by using constructor-based
or setter-based dependency injection.
Note:
1. For primitive data types use element and for dependent objects use
<ref bean="beanId"/>
2. Index attribute is used to specify the index of constructor arguments.
Example Explanation:
We have created two beans “Student” and “Address”. Student class requires an Address class object. In
spring configuration file we define Address bean and pass this as an argument in Student class using
constructor-arg element.
Example:
Student.java
package com.w3schools.business;
public class Student {
private String name;
private String rollNo;
private String className;
private Address address;
12 | P a g e
Spring Framework (Unit-5)
}
Address.java
package com.w3schools.business;
public class Address {
private String addLine;
private String city;
private String state;
private String country;
applicationContext.java
<?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">
13 | P a g e
Spring Framework (Unit-5)
</beans>
Test.java
package com.w3schools.business;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//Get ApplicationContext using spring configuration file.
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
14 | P a g e
Spring Framework (Unit-5)
Note:
1. For primitive data types use element and for dependent objects use
<ref bean="beanId"/>
2. Index attribute is used to specify the index of constructor arguments.
Example Explanation:
We have created two beans “Student” and “Address”. Student class requires an Address class object. In
spring configuration file we define Address bean and pass this as an argument in Student class using
parameter element.
Example:
Student.java
package com.w3schools.business;
public class Student {
private String name;
private String rollNo;
private String className;
private Address address;
Address.java
package com.w3schools.business;
public class Address {
15 | P a g e
Spring Framework (Unit-5)
</beans>
Test.java
16 | P a g e
Spring Framework (Unit-5)
package com.w3schools.business;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
17 | P a g e