UNIT-5 java
UNIT-5 java
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 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:
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.
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 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).
Web
The Web area provides support for building web applications. It includes the
following modules:
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:
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:
There can be various ways to get the resource to obtain the resource. Let's see the problem in this
approach.
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.
o By Constructor
o By Setter method
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:
We can achieve Inversion of Control through various mechanisms such as: Strategy
design pattern, Service Locator pattern, Factory pattern, and Dependency Injection
(DI).
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.
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
1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="10"></constructor-arg>
4. </bean>
5. ....
Output:0 10
1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="Sonoo"></constructor-arg>
4. </bean>
5. ....
Output:0 Sonoo
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 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.
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.
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.
package bean;
this.name = name;
return name;
}
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
< bean
id = "hw"
class= "bean.HelloWorld"
</beans>
package driver;
import org.springframework
.context.ApplicationContext;
import org.springframework
.context.support
.ClassPathXmlApplicationContext;
import bean.HelloWorld;
HelloWorld Geeks1
= (HelloWorld)ap.getBean("hw");
Geeks1.setName("Geeks1");
System.out.println(
+ Geeks1.getName());
// Get another "HelloWorld" bean object
HelloWorld Geeks2
= (HelloWorld)ap.getBean("hw");
System.out.println(
+ Geeks2.getName());
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
package bean;
this.name = name;
return name;
XML
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
< beans>
< bean
id = "hw"
class = "bean.HelloWorld"
Java
package driver;
import org.springframework
.context.ApplicationContext;
import org.springframework.context.support
.ClassPathXmlApplicationContext;
import bean.HelloWorld;
public class Client {
ApplicationContext ap
= new ClassPathXmlApplicationContext(
"resources/spring.xml");
HelloWorld Geeks1
= (HelloWorld)ap.getBean("hw");
Geeks1.setName("Geeks1");
System.out.println(
"Hello object (hello1)"
+ Geeks1.getName());
HelloWorld Geeks2
= (HelloWorld)ap.getBean("hw");
System.out.println(
+ Geeks2.getName());
System.out.println(
+ (Geeks1 == Geeks2));
System.out.println(
+ Geeks1);
System.out.println(
+ 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.
Singleton Prototype
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.
Singleton scope should be used for stateless While prototype scope is used for all
beans. beans that are stateful.