Professional Documents
Culture Documents
OOPS With Java Unit 5
OOPS With Java Unit 5
Unit :- 5
BCS-403
AKTU
Java Spring Framework
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
API designers prototype APIs using boilerplate code. Once the prototype is tested, developers can customize it to internal
specifications.
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.
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.