Unit-5 Spring Framework
Unit-5 Spring Framework
It was developed by Rod Johnson in 2003. Spring framework makes the easy
development of JavaEE application.
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.
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.
public TextEditor() {
spellChecker = new SpellChecker();
}
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.
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.
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.
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.
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
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.
● 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.
Syntax:
@AnnotationName
Example:
@Entity
Here @ symbol signals the compiler that this is an annotation and
the Entity is the name of this annotation.
@Entity(tableName = "USERS")
@Entity
public class Users {
}
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.
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.
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.
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.
Application Runner
Application Runner is an interface 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
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