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

Unit-5 Spring Framework

Uploaded by

vanshikaaa25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Unit-5 Spring Framework

Uploaded by

vanshikaaa25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Java Framework is the body or platform of pre-written codes used by Java developers

to develop Java applications or web applications. In other words, Java Framework is a


collection of predefined classes and functions that is used to process input, manage
hardware devices interacts with system software. It acts like a skeleton that helps the
developer to develop an application by writing their own code.

It was developed by Rod Johnson in 2003. Spring framework makes the easy
development of JavaEE application.

It is helpful for beginners and experienced persons.

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. We will learn these modules in next page. Let's understand the
IOC and Dependency Injection first.

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.
Let's take the example of JdbcTemplate, you don't need to write the code for exception
handling, creating connection, creating statement, committing transaction, closing
connection etc. You need to write the code of executing query only. Thus, it save a lot
of JDBC code.

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 - Dependency Injection


Every Java-based application has a few objects that work
together to present what the end-user sees as a working
application. When writing a complex Java application, application
classes should be as independent as possible of other Java
classes to increase the possibility to reuse these classes and to
test them independently of other classes while unit testing.
Dependency Injection (or sometime called wiring) helps in gluing
these classes together and at the same time keeping them
independent.

Consider you have an application which has a text editor


component and you want to provide a spell check. Your standard
code would look something like this −

public class TextEditor {


private SpellChecker spellChecker;

public TextEditor() {
spellChecker = new SpellChecker();
}

What we've done here is, create a dependency between the


TextEditor and the SpellChecker. In an inversion of control
scenario, we would instead do something like this −

public class TextEditor {


private SpellChecker spellChecker;

public TextEditor(SpellChecker spellChecker) {


this.spellChecker = spellChecker;
}
}
Here, the TextEditor should not worry about SpellChecker
implementation. The SpellChecker will be implemented
independently and will be provided to the TextEditor at the time
of TextEditor instantiation. This entire procedure is controlled by
the Spring Framework.

Here, we have removed total control from the TextEditor and kept
it somewhere else (i.e. XML configuration file) and the
dependency (i.e. class SpellChecker) is being injected into the
class TextEditor through a Class Constructor. Thus the flow of
control has been "inverted" by Dependency Injection (DI)
because you have effectively delegated dependances to some
external system.

The second method of injecting dependency is through Setter


Methods of the TextEditor class where we will create a
SpellChecker instance. This instance will be used to call setter
methods to initialize TextEditor's properties.

Dependency Injection is the main functionality provided by Spring


IOC(Inversion of Control). The Spring-Core module is responsible for injecting
dependencies through either Constructor or Setter methods. The design
principle of Inversion of Control emphasizes keeping the Java classes
independent of each other and the container frees them from object creation
and maintenance. These classes, managed by Spring, must adhere to the
standard definition of Java-Bean. Dependency Injection in Spring also ensures
loose coupling between the classes. There are two types of Spring
Dependency Injection.

1.Constructor-based dependency injection


Constructor-based DI is accomplished when the container
invokes a class constructor with a number of arguments, each
representing a dependency on the other class.

2.Setter-based dependency injection


Setter-based DI is accomplished by the container calling setter
methods on your beans after invoking a no-argument constructor
or no-argument static factory method to instantiate your bean.

You can mix both, Constructor-based and Setter-based DI but it


is a good rule of thumb to use constructor arguments for
mandatory dependencies and setters for optional dependencies.
The code is cleaner with the DI principle and decoupling is more
effective when objects are provided with their dependencies. The
object does not look up its dependencies and does not know the
location or class of the dependencies, rather everything is taken
care by the Spring Framework.

Spring IoC (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.

Spring IoC (Inversion of Control) Container is the core of Spring Framework. It


creates the objects, configures and assembles their dependencies, manages
their entire life cycle. The Container uses Dependency Injection(DI) to manage
the components that make up the application. It gets the information about the
objects from a configuration file(XML) or Java Code or Java Annotations and
Java POJO class. These objects are called Beans. Since the Controlling of
Java objects and their lifecycle is not done by the developers, hence the name
Inversion Of Control. The followings are some of the main features of Spring
IoC,
● Creating Object for us,
● Managing our objects,
● Helping our application to be configurable,
● Managing dependencies

AOP in Spring Framework


Aspect oriented programming(AOP) as the name suggests uses aspects in
programming. It can be defined as the breaking of code into different modules,
also known as modularisation, where the aspect is the key unit of modularity.
Aspects enable the implementation of crosscutting concerns such as-
transaction, logging not central to business logic without cluttering the code
core to its functionality. It does so by adding additional behaviour that is the
advice to the existing code. For example- Security is a crosscutting concern,
in many methods in an application security rules can be applied, therefore
repeating the code at every method, define the functionality in a common
class and control were to apply that functionality in the whole application.
Dominant Frameworks in AOP:
AOP includes programming methods and frameworks on which
modularisation of code is supported and implemented. Let’s have a look at
the three dominant frameworks in AOP:

● AspectJ: It is an extension for Java programming created at PARC


research centre. It uses Java like syntax and included IDE integrations for
displaying crosscutting structure. It has its own compiler and weaver, on
using it enables the use of full AspectJ language.
● JBoss: It is an open source Java application server developed by JBoss,
used for Java development.
● Spring: It uses XML based configuration for implementing AOP, also it uses
annotations which are interpreted by using a library supplied by AspectJ for
parsing and matching.
Currently, AspectJ libraries with Spring framework are dominant in the
market, therefore let’s have an understanding of how Aspect-oriented
programming works with Spring.

How Aspect-Oriented Programming works with Spring:


One may think that invoking a method will automatically implement
cross-cutting concerns but that is not the case. Just invocation of the method
does not invoke the advice(the job which is meant to be done). Spring
uses proxy based mechanism i.e. it creates a proxy Object which will wrap
around the original object and will take up the advice which is relevant to the
method call. Proxy objects can be created either manually through proxy
factory bean or through auto proxy configuration in the XML file and get
destroyed when the execution completes. Proxy objects are used to enrich the
Original behaviour of the real object.

A cross-cutting concern is a concern that can affect the whole application and should
be centralized in one location in code as possible, such as transaction management,
authentication, logging, security etc.

Common terminologies in AOP:


1. Aspect: The class which implements the JEE application cross-cutting
concerns(transaction, logger etc) is known as the aspect. It can be normal class
configured through XML configuration or through regular classes annotated with
@Aspect.
2. Weaving: The process of linking Aspects with an Advised Object. It can be
done at load time, compile time or at runtime time. Spring AOP does
weaving at runtime.
Let’s write our first aspect class but before that have a look at the jars
required and the Bean configuration file for AOP.

BEAN SCOPE
Bean Definition: In Spring, the objects that form the backbone of your
application and that are managed by the Spring IoC container are called
beans. A bean is an object that is instantiated, assembled, and otherwise
managed by a Spring IoC container.
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 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.
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.

Request Scope
In request scope, container creates a new instance for each and every HTTP
request. So, if the server is currently handling 50 requests, then the container
can have at most 50 individual instances of the bean class. Any state change
to one instance, will not be visible to other instances. A bean instance is
destructed as soon as the request is completed.

Session Scope
In session scope, the application context creates a new instance for each and
every HTTP session. So, if the server has 20 active sessions, then the
container can have at most 20 individual instances of the bean class. All HTTP
requests within a single session lifetime will have access to the same single
bean instance in that session scope.
Any state change to one instance will not be visible to other instances. An
instance is destructed as soon as the session ends.

Application Scope
In application scope, the container creates one instance per web application
runtime. It is almost similar to singleton scope with only two differences i.e.

1. The application scoped bean is singleton per ServletContext,


whereas singleton scoped bean is singleton per ApplicationContext.
Please note that there can be multiple application contexts within a
single application.

2. The application scoped bean is visible as a ServletContext attribute.

WebSocket Scope
The WebSocket Protocol enables two-way communication between a client
and a remote host that has opted-in to communicate with the client.
WebSocket Protocol provides a single TCP connection for traffic in both
directions. This is especially useful for multi-user applications with
simultaneous editing and multi-user games.
In this type of web application, HTTP is used only for the initial handshake.
The server can respond with HTTP status 101 (switching protocols) if it agrees
– to the handshake request. If the handshake succeeds, the TCP socket
remains open, and both the client and server can use it to send messages to
each other.
When first accessed, WebSocket scoped beans are stored in
the WebSocket session attributes. The same bean instance is then returned
during the entire WebSocket session.

Please note that websocket scoped beans are typically singleton and live
longer than any individual WebSocket session.

Autowiring in Spring
Autowiring in the Spring framework can inject dependencies automatically.
The Spring container detects those dependencies specified in the
configuration file and the relationship between the beans. This is referred to
as Autowiring in Spring. To enable Autowiring in the Spring application we
should use @Autowired annotation. Autowiring in Spring internally uses
constructor injection. An autowired application requires fewer lines of code
comparatively but at the same time, it provides very little flexibility to the
programmer.
Modes of Autowiring
Modes Description

This mode tells the framework that


No autowiring is not supposed to be done.
It is the default mode used by Spring.

It uses the name of the bean for


byName
injecting dependencies.

It injects the dependency according to


byType
the type of bean.

It injects the required dependencies by


Constructor
invoking the constructor.

Autodetect The autodetect mode uses two other


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.

Annotations
Annotations are a form of metadata that provides data about a program.
Annotations are used to provide supplemental information about a program. It
does not have a direct effect on the operation of the code they annotate. It
does not change the action of the compiled program. So in this article, we are
going to discuss what are the main types of annotation that are available in
the spring framework with some examples.

Use of java annotations


Java annotations are mainly used for the following:

● Compiler instructions
● Build-time instructions
● Runtime instructions
Compiler instructions: Java provides the 3 in built annotations
which are used to give certain instructions to the compiler. Java in
built annotation are @Deprecated, @Override &
@SuppressWarnings.

Build-time instructions: Java annotations can be used for build


time or compile time instructions. These instructions can be used by
the build tools for generating source code, compiling the source,
generating XML files, packaging the compiled code and files into a
JAR file etc.
Runtime instructions: Normally, Java annotations are not present
in your Java code after compilation. However, we can define our own
annotations that can be available at runtime. These annotations can
be accessed using Java Reflection.

Java annotations basics:


A java annotation always starts with the symbol @ and followed by
the annotation name. The @symbol signals the compiler that this is
an annotation.

Syntax:

@AnnotationName
Example:

@Entity
Here @ symbol signals the compiler that this is an annotation and
the Entity is the name of this annotation.

An annotation can contain zero, one or multiple elements. We have


to set values for these elements. Example:

@Entity(tableName = "USERS")

Where we can use annotations?


We can use java annotations above classes, interfaces, methods,
fields and local variables. Here is an example annotation added
above a class definition:

@Entity
public class Users {
}

Spring Bean Life Cycle and Callbacks


The lifecycle of any object means when & how it is born, how it behaves
throughout its life, and when & how it dies. Similarly, the bean life cycle refers
to when & how the bean is instantiated, what action it performs until it lives,
and when & how it is destroyed. In this article, we will discuss the life cycle of
the bean.
Bean life cycle is managed by the spring container. When we run the program
then, first of all, the spring container gets started. After that, the container
creates the instance of a bean as per the request, and then dependencies are
injected. And finally, the bean is destroyed when the spring container is
closed. Therefore, if we want to execute some code on the bean instantiation
and just after closing the spring container, then we can write that code inside
the custom init() method and the destroy() method.
The following image shows the process flow of the bean life cycle.

Bean Life Cycle Process Flow

Note: We can choose a custom method name instead of init() and destroy().
Here, we will use init() method to execute all its code as the spring container
starts up and the bean is instantiated, and destroy() method to execute all its
code on closing the container.

1. Spring bean life cycle involves initialization and destruction callbacks


and Spring bean aware classes.
2. Initialization callback methods execute after dependency injection is
completed. Their purposes are to check the values that have been set
in bean properties, perform any custom initialization or provide a
wrapper on original bean etc. Once the initialization callbacks are
completed, bean is ready to be used.
3. When IoC container is about to remove bean, destruction callback
methods execute. Their purposes are to release the resources held by
bean or to perform any other finalization tasks.
4. When more than one initialization and destructions callback
methods have been implemented by bean, then those methods
execute in certain order.

SPRING CONFIGURATION STYLE

Spring Framework provides three ways to configure beans to be used in the


application.

1. Annotation Based Configuration - By using @Service or @Component annotations.


Scope details can be provided with @Scope annotation.
2. XML Based Configuration - By creating Spring Configuration XML file to configure the
beans. If you are using Spring MVC framework, the xml based configuration can be loaded
automatically by writing some boiler plate code in web.xml file.
3. Java Based Configuration - Starting from Spring 3.0, we can configure Spring beans using
java programs. Some important annotations used for java based configuration
are @Configuration, @ComponentScan and @Bean.
Spring Boot
In Spring Boot, choosing a build system is an important task. We
recommend Maven or Gradle as they provide a good support for
dependency management. Spring does not support well other
build systems.

Dependency Management
Spring Boot team provides a list of dependencies to support the
Spring Boot version for its every release. You do not need to
provide a version for dependencies in the build configuration file.
Spring Boot automatically configures the dependencies version
based on the release. Remember that when you upgrade the
Spring Boot version, dependencies also will upgrade
automatically.

Note − If you want to specify the version for dependency, you can
specify it in your configuration file. However, the Spring Boot
team highly recommends that it is not needed to specify the
version for dependency.

Maven Dependency
For Maven configuration, we should inherit the Spring Boot
Starter parent project to manage the Spring Boot Starters
dependencies.

We should specify the version number for Spring Boot Parent


Starter dependency. Then for other starter dependencies, we do
not need to specify the Spring Boot version number.

Gradle Dependency
We can import the Spring Boot Starters dependencies directly
into build.gradle file. We do not need Spring Boot start Parent
dependency like Maven for Gradle.

SPRING BOOT CODE STRUCTURE


Spring Boot does not have any code layout to work with.
However, there are some best practices that will help us. This
chapter talks about them in detail.

Default package
A class that does not have any package declaration is considered
as a default package. Note that generally a default package
declaration is not recommended. Spring Boot will cause issues
such as malfunctioning of Auto Configuration or Component Scan,
when you use default package.

Note − Java's recommended naming convention for package


declaration is reversed domain name.

Spring Boot - Runners


Application Runner and Command Line Runner interfaces lets you
to execute the code after the Spring Boot application is started.
You can use these interfaces to perform any actions immediately
after the application has started. This chapter talks about them in
detail.

Application Runner
Application Runner is an interface used to execute the code after
the Spring Boot application started.

Command Line Runner


Command Line Runner is an interface. It is used to execute the
code after the Spring Boot application started.

LOGGER
Logging in Spring Boot plays a vital role in Spring Boot applications for recording
information, actions, and events within the app. It is also used for monitoring the
performance of an application, understanding the behavior of the application, and
recognizing the issues within the application. Spring Boot offers flexible logging
capabilities by providing various logging frameworks and also provides ways to
manage and configure the logs.
Why to use Spring Boot – Logging?
A good logging infrastructure is necessary for any software project as it not only helps
in understanding what’s going on with the application but also to trace any unusual
incident or error present in the project. This article covers several ways in which
logging can be enabled in a spring boot project through easy and simple
configurations. Let’s first do the initial setup to explore each option in more depth.
Elements of Logging Framework
● Logger: It captures the messages.
● Formatter: It formats the messages which are captured by loggers.
● Handler: It prints messages on the console, stores them in a file or sends an email,
etc.
Java provides several logging frameworks, some of which are:
1. Logback Configuration logging
2. Log4j2 Configuration logging

Introduction to RESTful Web Services


REST stands for REpresentational State Transfer. It is developed by Roy Thomas
Fielding, who also developed HTTP. The main goal of RESTful web services is to make
web services more effective. RESTful web services try to define services using the
different concepts that are already present in HTTP. REST is an architectural approach,
not a protocol.
It does not define the standard message exchange format. We can build REST services
with both XML and JSON. JSON is more popular format with REST. The key
abstraction is a resource in REST. A resource can be anything. It can be accessed
through a Uniform Resource Identifier (URI). For example:
The resource has representations like XML, HTML, and JSON. The current state capture
by representational resource. When we request a resource, we provide the
representation of the resource. The important methods of HTTP are:
o GET: It reads a resource.
o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.

For example, if we want to perform the following actions in the social media
application, we get the corresponding results.
POST /users: It creates a user.
GET /users/{id}: It retrieves the detail of a user.
GET /users: It retrieves the detail of all users.
DELETE /users: It deletes all users.
DELETE /users/{id}: It deletes a user.
GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.
POST / users/{id}/ posts: It creates a post of the user.
Further, we will implement these URI in our project.
HTTP also defines the following standard status code:
o 404: RESOURCE NOT FOUND
o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR

RESTful Service Constraints


o There must be a service producer and service consumer.
o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services


o RESTful web services are platform-independent.
o It can be written in any programming language and can be executed on any platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like SOAP.
o These are reusable.
o They are language neutral.

o RestController: RestController is used for making restful web services


with the help of the @RestController annotation. This annotation is used
at the class level and allows the class to handle the requests made by
the client. Let’s understand @RestController annotation using an
example. The RestController allows to handle all REST APIs such
as GET, POST, Delete, PUT requests.
o Spring Initializr is a web-based tool using which we can easily generate
the structure of the Spring Boot project. It also provides various different
features for the projects expressed in a metadata model. This model
allows us to configure the list of dependencies that are supported by
JVM. Here, we will create the structure of an application using a spring
initializer and then use an IDE to create a sample GET route.

You might also like