Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Object Oriented Programming with Java

Unit :- 5
BCS-403
AKTU
Java Spring Framework

What is Spring Framework?


Spring is a lightweight and popular open-source Java-based framework developed by Rod Johnson in
2003. It is used to develop enterprise-level applications. It provides support to many other frameworks
such as Hibernate, Tapestry, EJB, JSF, Struts, etc, so it is also called a framework of frameworks. 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.
Applications of Spring
POJO Based
Spring allows developers to use POJOs to create enterprise-class apps. The advantage of using simply
POJOs is that you don’t require an EJB container product like an application server; instead, you may
use a powerful servlet container like Tomcat or a commercial product.

Modular
Spring is set up in a modular approach. Even if there are a lot of packages and classes, you only need
to worry about the ones you need and ignore the rest.

Integration with existing frameworks


Spring does not reinvent the wheel; rather, it makes extensive use of existing technologies such as
numerous ORM frameworks, logging frameworks, JEE, Quartz, and JDK timers, and other view
technologies.

Testablity
Because environment-dependent code is put into this framework, testing a Spring-written application is
trivial. Furthermore, using JavaBeanstyle POJOs makes it easier to employ dependency injection for
injecting test data.

Web MVC
Spring’s web framework is a well-designed web MVC framework that is an excellent alternative to web
frameworks like Struts and other over-engineered or less popular web frameworks.
Central Exception Handling
Spring provides a handy API for converting technology-specific exceptions (such as those raised by
JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.
Lightweight
IoC containers are typically lightweight, especially when compared to EJB containers, for example. This
is useful for creating and distributing programmes on systems with limited memory and CPU resources.

Dependency Injection (DI) is a core concept in Spring Framework that allows for loose coupling between
objects by providing dependencies from external sources rather than creating them internally. This
promotes better code organization, maintainability, and testability.
Benefits of Dependency Injection:
 Loose coupling: Easier to modify and reuse components.
 Improved testability: Easier to write unit tests by injecting mock dependencies.
 Enhanced maintainability: Code is more organized and easier to understand.
Inversion of Control (IoC):
Dependency Injection is a form of Inversion of Control (IoC), a broader design principle where the control
of object creation and dependency management is transferred from the application code to a container
(Spring IoC Container).
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

Aspect Oriented Programming (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.

Why use AOP?

It provides the pluggable way to dynamically add the additional concern before, after or around the actual logic.

There are 5 methods that starts from m, 2 methods that starts from n and 3 methods that starts from p.

Understanding Scenario I have to maintain log and send notification after calling methods that starts from m.

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.

Bean Scopes
When defining a <bean> you have the option of declaring a scope for that bean. For example, to force
Spring to produce a new bean instance each time one is needed, you should declare the bean's scope
attribute to be prototype. Similarly, if you want Spring to return the same bean instance each time one is
needed, you should declare the bean's scope attribute to be singleton.

The Spring Framework supports the following five scopes, three of which are available only if you use a
web-aware ApplicationContext.

Sr.No. Scope & Description


1 singleton
This scopes the bean definition to a single instance per Spring IoC container
(default).
2 prototype
This scopes a single bean definition to have any number of object instances.
3 request
This scopes a bean definition to an HTTP request. Only valid in the context of a
web-aware Spring ApplicationContext.
4 session
This scopes a bean definition to an HTTP session. Only valid in the context of a
web-aware Spring ApplicationContext.
5 global-session
This scopes a bean definition to a global HTTP session. Only valid in the context
of a web-aware Spring ApplicationContext.

What is web socket and how it is different from the HTTP?


HTTP and WebSocket both are communication protocols used in client-server communication.
HTTP protocol: HTTP is unidirectional where the client sends the request and the server sends the
response. Let’s take an example when a user sends a request to the server this request goes in the
form of HTTP or HTTPS, after receiving a request server send the response to the client, each request
is associated with a corresponding response, after sending the response the connection gets closed,
each HTTP or HTTPS request establish the new connection to the server every time and after getting
the response the connection gets terminated by itself.
HTTP is a stateless protocol that runs on top of TCP which is a connection-oriented protocol it
guarantees the delivery of data packet transfer using the three-way handshaking methods and re-
transmits the lost packets.
HTTP can run on top of any reliable connection-oriented protocol such as TCP, SCTP. When a client
sends an HTTP request to the server, a TCP connection is open between the client and server and
after getting the response the TCP connection gets terminated, each HTTP request opens a separate
TCP connection to the server, for e.g. if the client sends 10 requests to the server the 10 separate TCP
connection will be opened. and get closed after getting the response/fallback.
HTTP message information encoded in ASCII, each HTTP request message composed HTTP protocol
version(HTTP/1.1, HTTP/2), HTTP methods (GET/POST, etc.), HTTP headers (content type, content
length), host information, etc. and the body which contain the actual message which is being
transferred to the server. HTTP headers varied from 200 bytes to 2 KB in size, the common size of
HTTP header is 700-800 bytes. When a web application uses more cookies and other tools at the
client-side that expand storage features of the agent it reduces the HTTP header payload.

Autowiring in Spring is a feature that allows the Spring container to automatically resolve and inject
dependencies into beans without the need for explicit configuration. It helps reduce the amount of XML or
Java configuration needed to wire beans together, making the code cleaner and easier to maintain.
Here's how autowiring works in Spring:
1. Enabling Autowiring:
@Autowired Annotation:
The most common way to enable autowiring is by using the @Autowired annotation on fields, constructors, or
setter methods within your Spring beans.
XML Configuration:
Alternatively, you can configure autowiring in your XML configuration file using the autowire attribute of the
<bean> tag.
2. Autowiring Modes:
byType:
This is the default mode. Spring tries to find a bean of the same type as the dependency to inject.
byName:
Spring looks for a bean whose name matches the name of the dependency property.
constructor:
Spring tries to find a constructor that matches the type of all the bean's dependencies.
no:
This is the default value if no autowiring is specified. It means no automatic wiring should be done.

Life Cycle of Call Back

the life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to
perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and
is removed from the container, some cleanup may be required.

Though, there are lists of the activities that take place behind the scene between the time of bean
Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback
methods, which are required at the time of bean initialization and its destruction.

To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-
method parameters. The init-method attribute specifies a method that is to be called on the bean
immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a
bean is removed from the container.
Bean Configuration Styles

There are several styles for configuring beans, including annotation-based, XML-based, and Java-based:
Annotation-based
Uses annotations like @Service, @Component, and @Scope to configure beans. For example, the @Bean
annotation can be used with any Spring @Component, but is most often used with @Configuration beans.
Annotating a class with @Configuration indicates that it's a source of bean definitions, and @Configuration
classes can define inter-bean dependencies by calling other @Bean methods.
XML-based
Uses a Spring Configuration XML file to configure beans. For example, if you're using Spring MVC, you can
write boiler plate code in web.xml to automatically load the XML-based configuration.
Java-based
Uses Java programs to configure beans, starting with Spring 3.0. Annotations like @Configuration,
@ComponentScan, and @Bean are used for Java-based configuration.
Spring Boot - Build Systems

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

For Maven configuration, we should inherit the Spring Boot Starter parent project to manage the Spring
Boot Starters dependencies. For this, simply we can inherit the starter parent in our pom.xml file

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.

ypical Layout

The typical layout of Spring Boot application is shown in the image given below −
The Application.java file should declare the main method along with @SpringBootApplication.
API
API stands for Application Programming Interface, and it's a set of rules that allows software programs to
communicate and share data with each other. APIs can be used for many things that involve computer
code, including operating systems, software libraries, and web applications.

How do APIs work?


API architecture is usually explained in terms of client and server. The application sending the request is called the client, and the
application sending the response is called the server. So in the weather example, the bureau’s weather database is the server, and the
mobile app is the client.

There are four different ways that APIs can work depending on when and why they were created.

SOAP APIs

These APIs use Simple Object Access Protocol. Client and server exchange messages using XML. This is a less flexible API that was
more popular in the past.

RPC APIs

These APIs are called Remote Procedure Calls. The client completes a function (or procedure) on the server, and the server sends the
output back to the client.
Websocket APIs

Websocket API is another modern web API development that uses JSON objects to pass data. A WebSocket API supports two-way
communication between client apps and the server. The server can send callback messages to connected clients, making it more
efficient than REST API.

REST APIs

These are the most popular and flexible APIs found on the web today. The client sends requests to the server as data. The server uses
this client input to start internal functions and returns output data back to the client. Let’s look at REST APIs in more detail below.

What are REST APIs?


REST stands for Representational State Transfer. REST defines a set of functions like GET, PUT, DELETE, etc. that clients can use to
access server data. Clients and servers exchange data using HTTP.

The main feature of REST API is statelessness. Statelessness means that servers do not save client data between requests. Client
requests to the server are similar to URLs you type in your browser to visit a website. The response from the server is plain data,
without the typical graphical rendering of a web page.

What is web API?


A Web API or Web Service API is an application processing interface between a web server and web browser. All web services are
APIs but not all APIs are web services. REST API is a special type of Web API that uses the standard architectural style explained
above.

The different terms around APIs, like Java API or service APIs, exist because historically, APIs were created before the world wide
web. Modern web APIs are REST APIs and the terms can be used interchangeably.
What are API integrations?
API integrations are software components that automatically update data between clients and servers. Some examples of API
integrations are when automatic data sync to the cloud from your phone image gallery, or the time and date automatically sync on your
laptop when you travel to another time zone. Enterprises can also use them to efficiently automate many system functions.

What are the benefits of REST APIs?


REST APIs offer four main benefits:

1. Integration

APIs are used to integrate new applications with existing software systems. This increases development speed because each
functionality doesn’t have to be written from scratch. You can use APIs to leverage existing code.

2. Innovation

Entire industries can change with the arrival of a new app. Businesses need to respond quickly and support the rapid deployment of
innovative services. They can do this by making changes at the API level without having to re-write the whole code.

3. Expansion

APIs present a unique opportunity for businesses to meet their clients’ needs across different platforms. For example, maps API allows
map information integration via websites, Android,iOS, etc. Any business can give similar access to their internal databases by using
free or paid APIs.
4. Ease of maintenance

The API acts as a gateway between two systems. Each system is obliged to make internal changes so that the API is not impacted.
This way, any future code changes by one party do not impact the other party.

What are the different types of APIs?


APIs are classified both according to their architecture and scope of use. We have already explored the main types of API architectures
so let’s take a look at the scope of use.

Private APIs

These are internal to an enterprise and only used for connecting systems and data within the business.

Public APIs

These are open to the public and may be used by anyone. There may or not be some authorization and cost associated with these
types of APIs.

Partner APIs

These are only accessible by authorized external developers to aid business-to-business partnerships.

Composite APIs

These combine two or more different APIs to address complex system requirements or behaviors.
What is an API endpoint and why is it important?
API endpoints are the final touchpoints in the API communication system. These include server URLs, services, and other specific
digital locations from where information is sent and received between systems. API endpoints are critical to enterprises for two main
reasons:

1. Security

API endpoints make the system vulnerable to attack. API monitoring is crucial for preventing misuse.

2. Performance

API endpoints, especially high traffic ones, can cause bottlenecks and affect system performance.

How to secure a REST API?


All APIs must be secured through proper authentication and monitoring. The two main ways to secure REST APIs include:

1. Authentication tokens

These are used to authorize users to make the API call. Authentication tokens check that the users are who they claim to be and that
they have access rights for that particular API call. For example, when you log in to your email server, your email client uses
authentication tokens for secure access.

2. API keys

API keys verify the program or application making the API call. They identify the application and ensure it has the access rights
required to make the particular API call. API keys are not as secure as tokens but they allow API monitoring in order to gather data on
usage. You may have noticed a long string of characters and numbers in your browser URL when you visit different websites. This
string is an API key the website uses to make internal API calls.

How to create an API?


Due diligence and effort are required to build an API that other developers will want to work with and trust. These are the five steps
required for high-quality API design:

1. Plan the API

API specifications, like OpenAPI, provide the blueprint for your API design. It is better to think about different use cases in advance and
ensure the API adheres to current API development standards.

2. Build the API

API designers prototype APIs using boilerplate code. Once the prototype is tested, developers can customize it to internal
specifications.

3. Test the API

API testing is the same as software testing and must be done to prevent bugs and defects. API testing tools can be used to strength
test the API against cyber attacks.

4. Document the API

While APIs are self-explanatory, API documentation acts as a guide to improve usability. Well-documented APIs that offer a range of
functions and use cases tend to be more popular in a service-oriented architecture.
5. Market the API

Just as Amazon is an online marketplace for retail, API marketplaces exist for developers to buy and sell other APIs. Listing your API
can allow you to monetize it.

You might also like