0% found this document useful (0 votes)
3 views

UNIT-5 java

The Spring Framework is a lightweight, open-source Java framework that supports the development of enterprise-level applications, providing infrastructure support and integration with various other frameworks. It features a modular architecture with core modules for dependency injection, data access, web applications, and security, allowing developers to build robust applications while managing complexity. Additionally, Spring promotes design patterns like Dependency Injection and Inversion of Control to enhance code maintainability and testability.

Uploaded by

SHILPI BANSAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

UNIT-5 java

The Spring Framework is a lightweight, open-source Java framework that supports the development of enterprise-level applications, providing infrastructure support and integration with various other frameworks. It features a modular architecture with core modules for dependency injection, data access, web applications, and security, allowing developers to build robust applications while managing complexity. Additionally, Spring promotes design patterns like Dependency Injection and Inversion of Control to enhance code maintainability and testability.

Uploaded by

SHILPI BANSAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

What is Spring Framework?

Spring is a lightweight and popular open-source Java-based framework developed


by Rod Johnson in 2003.

It is used to develop enterprise-level applications.

It provides support to many other frameworks such as Hibernate, Tapestry, EJB,


JSF, Struts etc, so it is also called a framework of frameworks.

It’s an application framework and IOC (Inversion of Control) container for the Java
platform. The spring contains several modules like IOC, AOP, DAO, Context, WEB
MVC, etc.

Spring Framework is a Java platform that provides comprehensive infrastructure


support for developing Java applications. Spring handles the infrastructure so you can
focus on your application.

Spring enables you to build applications from “plain old Java objects” (POJOs) and to
apply enterprise services non-invasively to POJOs. This capability applies to the Java
SE programming model and to full and partial Java EE.

Examples of how you, as an application developer, can use the Spring platform
advantage:

 Make a Java method execute in a database transaction without having to deal


with transaction APIs.
 Make a local Java method a remote procedure without having to deal with
remote APIs.
 Make a local Java method a management operation without having to deal with
JMX APIs.
 Make a local Java method a message handler without having to deal with JMS
APIs.
The Spring framework is modular and consists of several modules that provide
different functionalities to help build enterprise applications. The modules can be
broadly categorized into four main areas: Core Container, Data Access/Integration,
Web, and Miscellaneous. Let’s take a closer look at each area and its corresponding
modules:
Core Container

The Core Container provides the fundamental functionality of the Spring framework,
including the Inversion of Control (IoC) container and the ApplicationContext. It
includes the following modules:

Spring Core: This module provides the fundamental functionality of the Spring
framework, including IoC and DI. The IoC container is the heart of the Spring
Framework, responsible for creating and managing instances of JavaBeans. It uses
dependency injection to wire the beans together.

Spring Beans: This module provides the BeanFactory, which is the basic building
block of the IoC container, and the BeanWrapper, which is responsible for managing
the lifecycle of a bean. The Bean Factory is the core interface for accessing the IoC
container. It provides methods for retrieving beans.

Spring Context: This module provides the ApplicationContext, which is an advanced


version of the BeanFactory and provides additional features, such as
internationalization and resource loading, and the ability to publish and consume
events.

Spring Expression Language (SpEL): This module provides a powerful expression


language for querying and manipulating objects during runtime. SpEL supports a wide
range of features, including property access, method invocation, conditionals, loops,
and type conversion. It also provides support for accessing variables and functions
defined in the application context, as well as support for defining custom functions
and variables.

Data Access/Integration

The Data Access/Integration area provides support for integrating with databases and
other data sources. It includes the following modules:

Spring JDBC: This module provides a simple JDBC abstraction layer that reduces
the amount of boilerplate code required to work with JDBC. Spring JDBC provides
support for transaction management, allowing developers to manage database
transactions declaratively using Spring’s transaction management.

Spring ORM: This module provides integration with Object-Relational Mapping


(ORM) frameworks, such as Hibernate and JPA. Spring ORM provides a higher-level
abstraction layer on top of ORM frameworks, allowing developers to write less
boilerplate code and more easily integrate ORM technologies with other Spring
features, such as transaction management and caching.

Spring Data: This module provides a consistent and easy-to-use programming model
for working with data access technologies, including databases, NoSQL, and cloud-
based data services. Spring Data provides a wide range of features, including
automatic CRUD (Create, Read, Update, Delete) operations, query generation from
method names, support for pagination and sorting, integration with Spring’s
transaction management, and more. Additionally, Spring Data provides support for
common data access patterns, such as repositories and data access objects (DAOs).

Spring Transaction: This module provides support for declarative transaction


management in Spring applications. Spring Transaction provides support for various
transaction propagation and isolation levels, allowing developers to manage
transactions at different levels of granularity. Additionally, Spring Transaction
provides support for different transaction management strategies, such as using a JTA
transaction manager or a simple JDBC transaction manager.

Web

The Web area provides support for building web applications. It includes the
following modules:

Spring MVC: This module provides a Model-View-Controller (MVC) framework for


building web applications. Spring MVC provides a range of features, including
support for handling HTTP requests and responses, form handling, data binding,
validation, and more. It also provides support for different view technologies, such as
JSP (JavaServer Pages), Thymeleaf, and Velocity, allowing developers to choose the
view technology that best suits their needs.

Spring WebFlux: This module provides a reactive programming model for building
web applications that require high concurrency and scalability. Spring WebFlux
provides support for building reactive web applications using a range of technologies,
such as Netty, Undertow, and Servlet 3.1+ containers. It also provides a range of
features, including support for reactive data access, reactive stream processing, and
reactive HTTP clients.

Spring Web Services: This module provides support for building SOAP-based and
RESTful web services. Spring Web Services provides support for generating WSDL
(Web Services Description Language) from Java classes, and for generating Java
classes from WSDL. This allows developers to define the contract (i.e., the interface)
of their web service using WSDL, and to generate the Java classes that implement the
web service from the WSDL.

Miscellaneous

The Miscellaneous area includes other modules that provide additional functionality,
such as:

Spring Security: This module provides authentication and authorization features for
Spring applications. Spring Security provides a range of authorization mechanisms,
such as role-based access control and expression-based access control. It also provides
support for securing different parts of the application using different security
configurations, allowing developers to apply fine-grained security policies.

Spring Integration: This module provides support for building message-driven and
event-driven architectures. Spring Integration provides a range of integration patterns,
such as messaging, routing, and transformation. It provides support for a range of
messaging systems, such as JMS, AMQP, and Apache Kafka. It also provides support
for integrating with different protocols, such as FTP, HTTP, and TCP.

Spring Batch: This module provides support for batch processing and integration
with enterprise systems. Spring Batch provides a range of tools and utilities for
building and managing batch processing applications, such as support for testing and
debugging batch jobs, logging and monitoring, and integration with other Spring
modules, such as Spring Data and Spring Integration.

Spring Cloud: This module provides support for building cloud-native applications
using Spring technologies. Spring Cloud provides a range of features for building
cloud-native applications, such as service discovery, configuration management, and
load balancing. It provides support for integrating with different cloud platforms, such
as AWS and GCP, and for using different cloud-native technologies, such as
containers and serverless computing.

Overall, the Spring framework modules provide developers with a powerful set of
tools to build robust, scalable, and maintainable enterprise applications. The modular
architecture of the Spring framework allows developers to select only the necessary
modules for their specific needs, reducing unnecessary overhead and complexity in
the application.
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, Let's
understand the Dependency Lookup (DL) first:

Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can be
various ways to get the resource for example:

1. A obj = new AImpl();

In such way, we get the resource(instance of A class) directly by new keyword.

Another way is factory method:

2. A obj = A.getA();

This way, we get the resource (instance of A class) by calling the static factory method getA().

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

1. Context ctx = new InitialContext();


2. Context environmentCtx = (Context) ctx.lookup("java:comp/env");
3. A obj = (A)environmentCtx.lookup("A");

There can be various ways to get the resource to obtain the resource. Let's see the problem in this
approach.

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:

class Employee{
Address address;

Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}

In such case, instance of Address class is provided by external source such as XML file either by
constructor or setter method.

Two ways to perform Dependency Injection in Spring framework


Spring framework provides two ways to inject dependency

o By Constructor
o By Setter method

What Is Inversion of Control?


Inversion of Control is a principle in software engineering which transfers the control
of objects or portions of a program to a container or framework. We most often use it
in the context of object-oriented programming.
In contrast with traditional programming, in which our custom code makes calls to a
library, IoC enables a framework to take control of the flow of a program and make
calls to our custom code. To enable this, frameworks use abstractions with additional
behavior built in.

If we want to add our own behavior, we need to extend the classes of the
framework or plugin our own classes.
The advantages of this architecture are:

 decoupling the execution of a task from its implementation


 making it easier to switch between different implementations
 greater modularity of a program
 greater ease in testing a program by isolating a component or mocking its
dependencies, and allowing components to communicate through contracts

We can achieve Inversion of Control through various mechanisms such as: Strategy
design pattern, Service Locator pattern, Factory pattern, and Dependency Injection
(DI).

Dependency Injection by Constructor


Example
1. Dependency Injection by constructor
2. Injecting primitive and string-based values

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
Let's see the simple example to inject primitive and string-based values. We
have created three files here:

o Employee.java
o applicationContext.xml
o 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.

1. package com.javatpoint;
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

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.

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.javatpoint.Employee">
10.<constructor-arg value="10" type="int"></constructor-arg>
11.</bean>
12.
13.</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the
show method.

1. package com.javatpoint;
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"); //for retrieving a bean instance from
the Spring container.
14. s.show();
15.
16. }
17.}

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.

1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="10"></constructor-arg>
4. </bean>
5. ....

If you change the bean element as given above, string parameter


constructor will be invoked and the output will be 0 10.

Output:0 10

You may also pass the string literal as following:

1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="Sonoo"></constructor-arg>
4. </bean>
5. ....

Output:0 Sonoo

You may pass integer literal and string both as following

1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="10" type="int" ></constructor-arg>
4. <constructor-arg value="Sonoo"></constructor-arg>
5. </bean>
6. ....

Output:10 Sonoo

Bean Scopes in Java Spring




Bean Scopes refers to the lifecycle of Bean that means when the
object of Bean will be instantiated, how long does that object live,
and how many objects will be created for that bean throughout.
Basically, it controls the instance creation of the bean and it is
managed by the spring container.

Bean Scopes in Spring

The spring framework provides five scopes for a bean. We can use
three of them only in the context of web-aware Spring
ApplicationContext and the rest of the two is available for
both IoC container and Spring-MVC container. The following are
the different scopes provided for a bean:
1. Singleton: Only one instance will be created for a single bean
definition per Spring IoC container and the same object will be
shared for each request made for that bean.
2. Prototype: A new instance will be created for a single bean
definition every time a request is made for that bean.
3. Request: A new instance will be created for a single bean
definition every time an HTTP request is made for that bean. But
only valid in the context of a web-aware Spring
ApplicationContext.
4. Session: Scopes a single bean definition to the lifecycle of an
HTTP Session. But only valid in the context of a web-aware Spring
ApplicationContext.
5. Global-Session: Scopes a single bean definition to the lifecycle
of a global HTTP Session. It is also only valid in the context of a
web-aware Spring ApplicationContext.

Let’s us see some of them in detail:

Singleton Scope:

If the scope is a singleton, then only one instance of that bean will
be instantiated per Spring IoC container and the same instance will
be shared for each request. That is when the scope of a bean is
declared singleton, then whenever a new request is made for that
bean, spring IOC container first checks whether an instance of that
bean is already created or not. If it is already created, then the IOC
container returns the same instance otherwise it creates a new
instance of that bean only at the first request. By default, the scope
of a bean is a singleton.
Let’s understand this scope with an example.

 Step1: Lets first create a bean (i.e.), the backbone of the


application in the spring framework.
 Java
// Java program to illustrate a bean

// created in the spring framework

package bean;

public class HelloWorld {

public String name;

// Create a setter method to

// set the value passed by user

public void setName(String name)

this.name = name;

// Create a getter method so that

// the user can get the set value

public String getName()

return name;
}

 Step 2: Now, we write a Spring XML configuration


file “spring.xml” and configure the bean defined above.
 XML

<!DOCTYPE beans PUBLIC

"-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<!--configure the bean HelloWorld.java

and declare its scope-->

< bean

id = "hw"

class= "bean.HelloWorld"

scope = "singleton" / >

</beans>

 Step 3: Finally, write a driver class “Client.java” to request the


above bean.
 Java

// Java program to illustrate


// the client to perform the

// request to the defined bean

package driver;

import org.springframework

.context.ApplicationContext;

import org.springframework

.context.support

.ClassPathXmlApplicationContext;

import bean.HelloWorld;

// Client Class to request the

// above defined bean

public class Client {


public static void main(String[] args)

// Load the Spring XML configuration

// file into IoC container

ApplicationContext ap = new ClassPathXmlApplicationContext(resources/spring.xml");

// Get the "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks1

= (HelloWorld)ap.getBean("hw");

// Set the name

Geeks1.setName("Geeks1");

System.out.println(

"Hello object (hello1)"

+ " Your name is: "

+ Geeks1.getName());
// Get another "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks2

= (HelloWorld)ap.getBean("hw");

System.out.println(

"Hello object (hello2)"

+ " Your name is: "

+ Geeks2.getName());

// Now compare the references to see

// whether they are pointing to the

// same object or different object

System.out.println("'Geeks1' and 'Geeks2'" + " are referring"+

"to the same object: " + (Geeks1 == Geeks2));

// Print the address of both

// object Geeks1 and Geeks2

System.out.println("Address of object Geeks1: "+ Geeks1);


System.out.println("Address of object Geeks2: "+ Geeks2);

 Output:
Hello object (hello1) Your name is: Geeks1
Hello object (hello2) Your name is: Geeks1
'Geeks1' and 'Geeks2' are referring to the same object: true
Address of object Geeks1: bean.HelloWorld@627551fb
Address of object Geeks2: bean.HelloWorld@627551fb
 Explanation: When we call the getName() method by using the
reference of ‘Geeks1’ and ‘Geeks2’, then we are getting the same
outputs. This means that both the reference is calling the
getName() method of the same object. Furthermore, when we are
comparing the reference ‘Geeks1’ and ‘Geeks2’ then output is
“true” which means the same object is shared between ‘Geeks1’
and ‘Geeks2’. So it is clear that a new instance of bean
(HelloWorld) is created when we made the request the first time
and for each new request, the same object is being shared.

Prototype Scope:

If the scope is declared prototype, then spring IOC container will create a
new instance of that bean every time a request is made for that specific
bean. A request can be made to the bean instance either programmatically
using getBean() method or by XML for Dependency Injection of secondary
type. Generally, we use the prototype scope for all beans that are stateful,
while the singleton scope is used for the stateless beans.
Let’s understand this scope with an example:
 Step 1: Let us first create a bean (i.e.), the backbone of the application in
the spring framework.

 Java

// Java program to illustrate a bean

// created in the spring framework

package bean;

public class HelloWorld {

public String name;

// Create a setter method to

// set the value passed by user

public void setName(String name)

this.name = name;

// Create a getter method so that

// the user can get the set value


public String getName()

return name;

 Step 2: Now, we write a Spring XML configuration file “spring.xml” and


configure the bean defined above.

 XML

<!DOCTYPE beans PUBLIC

"-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

< beans>

<!--configure the bean HelloWorld.java

and declare its scope-->

< bean

id = "hw"

class = "bean.HelloWorld"

scope = "prototype" / >


</ beans>

 Step 3: Finally, write a driver class “Client.java” to request the above


bean.

 Java

// Java program to illustrate

// the client to perform the

// request to the defined bean

package driver;

import org.springframework

.context.ApplicationContext;

import org.springframework.context.support

.ClassPathXmlApplicationContext;

import bean.HelloWorld;
public class Client {

public static void main(String[] args)

// Load the Spring XML configuration

// file into IoC container

ApplicationContext ap

= new ClassPathXmlApplicationContext(

"resources/spring.xml");

// Get the "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks1

= (HelloWorld)ap.getBean("hw");

// Set the name

Geeks1.setName("Geeks1");

System.out.println(
"Hello object (hello1)"

+ " Your name is: "

+ Geeks1.getName());

// Get another "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks2

= (HelloWorld)ap.getBean("hw");

System.out.println(

"Hello object (hello2)"

+ "Your name is: "

+ Geeks2.getName());

// Now compare the references to see

// whether they are pointing to the

// same object or different object

System.out.println(

"'Geeks1' and 'Geeks2'"


+ "are referring "

+ "to the same object: "

+ (Geeks1 == Geeks2));

// Print the address of both

// object Geeks1 and Geeks2

System.out.println(

"Address of object Geeks1: "

+ Geeks1);

System.out.println(

"Address of object Geeks2: "

+ Geeks2);

 Output:
Hello object (hello1) Your name is: Geeks1
Hello object (hello2) Your name is: null
'Geeks1' and 'Geeks2' are referring to the same object: false
Address of object Geeks1: bean.HelloWorld@47ef968d
Address of object Geeks2: bean.HelloWorld@23e028a9
 Explanation: When we call getName() method by using the reference
‘Geeks1’ and ‘Geeks2’, then we get different outputs that means both the
reference is calling getName() method of a different object. Furthermore,
when we are comparing the reference ‘Geeks1’ and ‘Geeks2’ then output
is “false” which means both references is referring to a different object. So
it is clear that a new instance of bean (HelloWorld) is being created at
each request made for this bean.

Difference between Singleton and Prototype

Singleton Prototype

A new instance is created for a single


Only one instance is created for a single
bean definition every time a request is
bean definition per Spring IoC container
made for that bean.

Same object is shared for each request made For each new request a new instance is
for that bean. i.e. The same object is created. i.e. A new object is created each
returned each time it is injected. time it is injected.

By default scope of a bean is singleton. So By default scope is not prototype so you


we don’t need to declare a bean as singleton have to declare the scope of a bean as
explicitly. prototype explicitly.

Singleton scope should be used for stateless While prototype scope is used for all
beans. beans that are stateful.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy