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

OOPS With Java Unit 5

Uploaded by

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

OOPS With Java Unit 5

Uploaded by

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

Object Oriented Programming with Java

Unit :- 5
Spring Framework and Spring Boot

A Java framework is the body of predefined codes used by


programmers to develop applications on the web. These frameworks
in Java development are classes and functions that control hardware,
process input, and communicate with system applications.
SPRING FRAMEWORK
Spring framework makes the easy development of JavaEE application.

It is helpful for beginners and experienced persons.

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.
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.
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.
There are two types of Spring Dependency Injection.

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

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, we are going to
discuss what are the main types of annotation that are available in the spring framework .
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.
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.
BEAN 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 is most commonly used and contains all Spring Framework features.
Nowadays Spring Boot is becoming the best choice for Java developers to build rapid
Spring applications. When Java Developers use Spring Boot for developing applications
then they will focus on the logic instead of struggling with the configuration setup
environment of the application.

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.
SPRING BOOT CODE STRUCTURE

Note: It is recommended to use Java’s package


naming conventions with a reverse domain name.
Rest Controller
When building robust APIs, understanding and appropriately utilizing the HTTP methods GET, POST, PUT, and
DELETE is essential. Each method serves a specific purpose and has its own limitations. We will explore these
HTTP methods, their characteristics, and discuss their limitations in the context of building robust APIs. Additionally,
we will provide Java code examples to demonstrate their usage.

HTTP methods, also known as HTTP verbs, are a set of standardized actions that can be performed on a resource
using the Hypertext Transfer Protocol (HTTP). These methods define the intended operation to be performed on the
resource and provide a uniform way of interacting with web servers. The most commonly used HTTP methods are
GET, POST, PUT, and DELETE, but there are other methods as well, such as PATCH, HEAD, and OPTIONS.

HTTP methods are important for several reasons:

By understanding and utilizing the appropriate HTTP methods, developers can build robust and well-designed
APIs that adhere to the principles of HTTP and REST. This ensures consistency, interoperability, and efficiency
in the communication between clients and servers.
Below we will elaborate more on the most commonly used HTTP methods.
Here are some key points to consider when working with the GET method in API development:
The POST method is one of the HTTP methods used for submitting data to be processed by the server.
Unlike the GET method, which is used for retrieving data, the POST method is intended for data
submission and can cause modifications on the server. Here are some important points to consider when
working with the POST method:
The PUT method is an HTTP method used for updating or replacing a resource on the server. It is
idempotent, meaning that multiple identical PUT requests should have the same outcome. Here are
some important points to consider when working with the PUT method:

In the provided Java code example, a PUT request is sent to https://api.example.com/resource with a request body containing the updated
data. The data is written to the request output stream, and the response code is checked to handle the response accordingly.
When using the PUT method, it is important to handle concurrency and data consistency issues appropriately. For example, you may use optimistic
locking mechanisms or versioning to ensure that updates do not conflict with other concurrent modifications to the resource.
Remember to use the appropriate HTTP method based on the intended operation. While the GET method is used for retrieving data and the POST
method is used for submitting data, the PUT method is suitable for updating existing resources on the server.
The DELETE method is an HTTP method used for deleting a specified resource on the server. It is
used to remove a resource permanently from the server. Here are some important points to consider
when working with the DELETE method:

In the provided Java code example, a DELETE request is sent to https://api.example.com/resource/123, where “123” represents the identifier of the
resource to be deleted. The response code is checked to handle the success or failure of the deletion operation.
When using the DELETE method, it is important to implement proper authorization and authentication mechanisms to prevent unauthorized deletions.
Additionally, consider providing proper error handling and feedback to the client in case of failures or errors during the deletion process.
Remember to use the appropriate HTTP method based on the intended operation. While the GET method is used for retrieving data, the POST method is
used for submitting data, the PUT method is used for updating data, the DELETE method is specifically designed for resource deletion.
One of the most important annotations in spring is the @RequestMapping Annotation which
is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC
applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP
requests to handler methods of controllers. When configuring Spring MVC, you need to specify the
mappings between the requests and handler methods.
What is Request Body?
Data sent over the request body can be of any format like json, XML, PDF, Http Forms, and many more. The Content-
Type header indicates the server's understanding type of request.
Spring provides @RequestBody annotation to deserialize the incoming payload into java object or map.
The request body goes along with content-type header for handler method to understand and deserialize the payload.

How to Get the Body of Request in Spring Boot?


Java language is one of the most popular languages among all programming languages. There are several
advantages of using the Java programming language, whether for security purposes or building large
distribution projects. One of the advantages of using Java is that Java tries to connect every concept in the
language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc.
There are several other concepts present in Java that increase the user-friendly interaction between the Java
code and the programmer such as generic, Access specifiers, Annotations, etc. These features add an extra
property to the class as well as the method of the Java program. In this article, we will discuss how to get the
body of the incoming request in the spring boot.

@RequestBody: Annotation is used to get the request body in the incoming request.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot
project. It also provides various 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. Therefore, to do this,
the following steps are followed sequentially as follows:
Path variable in spring boot
The @PathVariable annotation is used to retrieve data from the URL path. By defining
placeholders in the request mapping URL, you can bind those placeholders to method
parameters annotated with @PathVariable. This allows you to access dynamic values from the
URL and use them in your code.
The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in
the request mapping URL, you can bind those placeholders to method parameters annotated with
@PathVariable. This allows you to access dynamic values from the URL and use them in your code.
The @PathVariable annotation is used to extract data from the URL path.
It allows you to define placeholders in your request mapping URL and bind
those placeholders to method parameters.
Build Web Applications
Java is one of the most used programming languages for developing dynamic web applications. A web application
is computer software that utilizes the web browser and technologies to perform tasks over the internet. A web
application is deployed on a web server.
Java provides some technologies like Servlet and JSP that allow us to develop and deploy a web application on a
server easily. It also provides some frameworks such as Spring, Spring Boot that simplify the work and provide an
efficient way to develop a web application. They reduce the effort of the developer.
We can create a website using static HTML pages and style them using CSS, but we need server-side technology
when we want to create a dynamic website

A web application is computer software that can be accessed using any web browser. Usually, the frontend of
a web application is created using the scripting languages such as HTML, CSS, and JavaScript, supported
by almost all web browsers. In contrast, the backend is created by any of the programming languages such
as Java, Python, Php, etc., and databases. Unlike the mobile application, there is no specific tool for
developing web applications; we can use any of the supported IDE for developing the web application.
We use the concept of MVC, i.e., Model-View-Controller.
MVC is an architecture that separates various
components of an application like the Input Logic,
Business Logic, and UI Logic.
The views and the models don’t interact with each other.
The controller receives the request from the view and
gets the required details from the model and transfers it

AT THE END YOUR TASK :-


Build a Web Application
using Java , Spring etc.

For E.g:- To do List ,


Calculator etc.

You might also like