0% found this document useful (0 votes)
8 views21 pages

Unit-5 Oopj PDF

Uploaded by

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

Unit-5 Oopj PDF

Uploaded by

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

UNIT- 5th

Spring F ramework

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.

Advantages of Spring Framework

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.

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.
Basics-Spring Dependency Injection concepts

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:

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.

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:

1. class Employee{
2. Address address;
3.
4. Employee(Address address){
5. this.address=address;
6. }
7. public void setAddress(Address address){
8. this.address=address;
9. }
10.
11.}

Spring Inversion of Control

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.

There are 2 types of IoC containers:

That means if you want to use an IoC container in spring whether we


need to use a BeanFactory or ApplicationContext. The BeanFactory is
the most basic version of IoC containers, and the ApplicationContext
extends the features of BeanFactory. 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

Spring AOP

Aspect Oriented P rogramming (AOP) compliments OOPs in the sense


that it also provides modularity. But the key unit of modularity is aspect
than class.

AOP breaks the program logic into distinct parts (called concerns). It is
used to increase modularity by cross-cutting concerns.

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.

Problem without AOP We can call methods (that maintains log and
sends notification) from the methods starting with m. In such scenario,
we need to write the code in all the 5 methods.

But, if client says in future, I don't have to send notification, you need to
change all the methods. It leads to the maintenance problem.

Solution with AOP We don't have to call methods from the method.
Now we can define the additional concern like maintaining log, sending
notification etc. in the method of a class. Its entry is given in the xml
file.

In future, if client says to remove the notifier functionality, we need to


change only in the xml file. So, maintenance is easy in AOP.
AOP Concepts and Terminology
AOP concepts and terminologies are as follows:

o Join point
o Advice
o Pointcut
o Introduction
o Target Object
o Aspect
o Interceptor
o AOP Proxy
o Weaving

Join point

Join point is any point in your program such as method execution,


exception handling, field access etc. Spring supports only method
execution join point.

Pointcut

It is an expression language of AOP that matches join points.

Introduction

It means introduction of additional method and fields for a type. It


allows you to introduce new interface to any advised object.
Aspect

It is a class that contains advices, joinpoints etc.

Interceptor

It is an aspect that contains only one advice.

AOP Proxy

It is used to implement aspect contracts, created by AOP framework. It


will be a JDK dynamic proxy or CGLIB proxy in spring framework

Weaving

It is the process of linking aspect with other application types or objects


to create an advised object. Weaving can be done at compile time, load
time or runtime. Spring AOP performs weaving at runtime

AOP Implementations
AOP implementations are provided by:

1. AspectJ
2. Spring AOP
3. JBoss AOP
Singleton and Prototype 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.

Spring Boot – Web Socket

WebSocket is used as a communication protocol that provides full-


duplex communication channels over a single, long-lived connection
between a client and a server. In this protocol, there are no restrictions
like HTTP that for a response you have to make a request first.
The server can send the message without getting any request and this
can be useful in many applications like

 Chat applications
 Sending any notification to the user
 And many more.

In HTTP client has to request only the response or the payload from
the server will be given and then the connection is terminated. Now if
you require further payload or data then you have to repeat the whole
process.
 WebSocket client establishes the socket connection with the server
and receives the message or data without any refresh
 The connection won’t be terminated which means that we can
again receive the message.
Also, WebSocket is a bi-directional protocol which means that the
server and client can exchange the message in parallel and it decreases
the round trip and the time for response. An application like trading,
monitoring, or creating functionality like notifications WebSocket is
very useful.
Creating a Chat Application using WebSocket in Spring Boot

1. Initialize the P roject


So, using WebSocket we will create a chat application where two
clients can connect to the server using the client application and they
can exchange the message through sockets.

2. Handling WebSocket’s Connections – Handler F ile


First, we have to create a file that can handle the operations of the
WebSocket. We will extend the class TextWebSocketHandler and
using that we will manage some operations.
So, We want to manage
1. The function that can handle the First-time connection from the
user.
2. Functions that can handle when the user Disconnects from the
server
3. Users exchange the messages

3. Code For Creating Socket in Spring Boot – Configuration File


Now we can manage the socket connection so it is a time to create an
endpoint where the socket can be found. But for that, we want to create
a configuration file so that Middleware intercepts the incoming
request.

4. Testing the Socket Connection


We can test whether the sockets are working fine or not in Postman.
Just change the request type to WebSocket put the endpoint and click
on Connect and then you can send the message to the socket. In the
below image first we establish the connection and then we send a
Hello message to the network.

Autowiring in Spring

Autowiring feature of spring framework enables you to inject the object


dependency implicitly. It internally uses setter or constructor injection.

Autowiring can't be used to inject primitive and string values. It works


with reference only.

Example of Autowiring
Let's see the simple code to use autowiring in spring. You need to use
autowire attribute of bean element to apply the autowire modes.

Let's see the full example of autowiring in spring. To create this


example, we have created 4 files.

1. B.java
2. A.java
3. applicationContext.xml
4. Test.java
Bean life cycle in Java Spring

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.

1. By XML: In this approach, in order to avail custom init() and


destroy() methods for a bean we have to register these two methods
inside the Spring XML configuration file while defining a bean .

2. By P rogrammatic Approach: To provide the facility to the created


bean to invoke custom init() method on the startup of a spring
container and to invoke the custom destroy() method on closing the
container, we need to implement our bean with two interfaces
namely InitializingBean, DisposableBean and will have to
override afterP ropertiesSet() and destroy() method. afterP roperties
Set() method is invoked as the container starts and the bean is
instantiated whereas, the destroy() method is invoked just after the
container is closed.

Bean Configuration styles

Different Methods to Create a Spring Bean

Here we are going to discuss how to create a Spring Bean in 3 different


ways as follows:
1. Creating Bean Inside an XML Configuration File (beans.xml)
2. Using @Component Annotation
3. Using @Bean Annotation

Method 1: Creating Bean Inside an XML Configuration F ile


(beans.xml)

One of the most popular ways to create a spring bean is to define a


bean in an XML configuration file something like this.
<bean id="AnyUniqueId" class="YourClassName">
</bean>
Let us create a simple class Student having two attributes id and
studentName and later creating a simple method to print the details of
the student.
Method 2: Using @Component Annotation

Spring 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. @Component is an annotation that allows Spring to
automatically detect the custom beans .

Method 3: Using @Bean Annotation

One of the most important annotations in spring is the @Bean


annotation which is applied on a method to specify that it returns a
bean to be managed by Spring context. Spring Bean annotation is
usually declared in Configuration classes methods.
Suppose we have already a Java project and all the Spring JAR files
are imported into that project. Now let’s create a simple class named
College and inside the class, we have a simple method. Below is the
code for the College.java file.

What is Spring Boot

Spring Boot is a project that is built on the top of the Spring Framework.
It provides an easier and faster way to set up, configure, and run both
simple and web-based applications.

It is a Spring module that provides the RAD (Rapid Application


Development) feature to the Spring Framework. It is used to create a
stand-alone Spring-based application that you can just run because it
needs minimal Spring configuration.
o The dependency injection approach is used in Spring Boot.
o It contains powerful database transaction management capabilities.
o It simplifies integration with other Java frameworks like
JPA/Hibernate ORM, Struts, etc.
o It reduces the cost and development time of the application.

Advantages of Spring Boot

o It creates stand-alone Spring applications that can be started using


Java -jar.
o It tests web applications easily with the help of
different Embedded HTTP servers such as Tomcat, Jetty, etc. We
don't need to deploy WAR files.
o It provides opinionated 'starter' POMs to simplify our Maven
configuration.
o It provides production-ready features such as metrics, health
checks, and externalized configuration.
o There is no requirement for XML configuration.
o It offers a CLI tool for developing and testing the Spring Boot
application.
o It offers the number of plug-ins.
o It also minimizes writing multiple boilerplate codes (the code that
has to be included in many places with little or no alteration),
XML configuration, and annotations.
o It increases productivity and reduces development time.

Goals of Spring Boot


The main goal of Spring Boot is to reduce development, unit
test, and integration test time.

o Provides Opinionated Development approach


o Avoids defining more Annotation Configuration
o Avoids writing lots of import statements
o Avoids XML Configuration.

Spring Boot Features

o Web Development
o SpringApplication
o Application events and listeners
o Admin features
o Externalized Configuration
o Properties Files
o YAML Support
o Type-safe Configuration
o Logging
o Security

Spring Boot Code Structure

There is no specific layout or code structure for Spring Boot Projects.


However, there are some best practices followed by developers that
will help us too. You can divide your project into layers like service
layer, entity layer, repository layer,, etc. You can also divide the
project into modules. For example, the parent project has two child
modules. The first module is for the data layer and the second module
is for the web layer. You can also divide the project into features.

Let us discuss two approaches that are typically used by most


developers to structure their spring boot projects.
1. Structure by Feature
2. Structure by Layer

The advantages of this structure is as follows:


 Find a class to be modified is easy.
 By deleting a particular sub-package, all the classes related to a
certain feature can be deleted.
 Testing and Refactoring is easy.
 Features can be shipped separately.
Spring Boot – Runners

Application Runner

Application Runner is an interface used to execute the code after the


Spring Boot application started. The example given below shows how to
implement the Application Runner interface on the main class file.

Command Line Runner

Command Line Runner is an interface. It is used to execute the code


after the Spring Boot application started. The example given below
shows how to implement the Command Line Runner interface on the
main class file.

BUILDING 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).
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.

Request Parameter

In Spring MVC, the @RequestParam annotation is used to read the


form data and bind it automatically to the parameter present in the
provided method. So, it ignores the requirement
of HttpServletRequest object to read the provided data.
Including form data, it also maps the request parameter to query
parameter and parts in multipart requests. If the method parameter type
is Map and a request parameter name is specified, then the request
parameter value is converted to a Map else the map parameter is
populated with all request parameter names and values.

1. Add dependencies to pom.xml


2. Create the request page
3. Create the Controller Class
4. Create the other view components

Spring Boot CRUD Operations

What is the CRUD operation?

The CRUD stands for Create, Read/Retrieve, Update, and Delete.


These are the four basic functions of the persistence storage.

The CRUD operation can be defined as user interface conventions that


allow view, search, and modify information through computer-based
forms and reports. CRUD is data-oriented and the standardized use
of HTTP action verbs. HTTP has a few important verbs.

o POST: Creates a new resource


o GET: Reads a resource
o PUT: Updates an existing resource
o DELETE: Deletes a resource

Standard CRUD Operation


o CREATE Operation: It performs the INSERT statement to create
a new record.
o READ Operation: It reads table records based on the input
parameter.
o UPDATE Operation: It executes an update statement on the table.
It is based on the input parameter.
o DELETE Operation: It deletes a specified row in the table. It is
also based on the input parameter.

Build Web Applications

Developer productivity
Battle-tested security
Data access made easy

You might also like