Unit5_OOPSwithjava
Unit5_OOPSwithjava
Spring Framework
Spring Framework
• Open-Source Framework
• Standalone and Enterprise application can be developed
• Released in 2003(initial), 2004(production) developed by Rod Johnson
• 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.
Advantages
• Modular and lightweight(lightweight and easy to maintain applications)
• Flexible configuration(supports Java-based, XML-based and annotation-
based configurations)
• Dependency Injection(dependency management)
• Aspect oriented programming(Allows developers to separate code from the
features like logging, transactions, security etc.)
• Easy database handling(reduce boilerplate code increase efficiency)
• Testing support
• Security(robust framework for implementing authentication, authorization)
• High integration capabilities(with other frameworks and technologies like
angular, react, JMS, SOAP, REST)
• High Scalability
• Open-Source
Modules
The Spring
Framework consists
of features organized
into about 20
modules. These
modules are grouped
into Core Container,
Data
Access/Integration,
Web, AOP (Aspect
Oriented
Programming),
Instrumentation, and
Test, as shown in the
following diagram.
Dependency?
• Example of dependency
• Code has very high degree of coupling due to aggregation
• To create Object of class Person, we depend on Address Object, and
to create Address object, we need contact
Spring Container
• The Spring container is the core of the Spring Framework.
• Manages Bean Objects(create, initialize, destroy)[Life cycle of bean]
• It is responsible for creating, configuring, and managing the objects
that make up your application.
• The container uses a technique called dependency injection to
manage the relationships between objects.
• Transaction Management
Spring container are of TWO TYPES
1. BeanFactory(old Method)
2. ApplicationContext(new Method)
Working of Spring Container
Working of Spring Container
Working of Spring Container
Spring Framework Example with Java Configuration file
Inversion of Control (IoC)
• Inversion of Control (IoC) is a design principle that emphasizes keeping Java
classes independent of each other.
• IoC is achieved through Dependency Injection (DI).
• IoC refers to transferring the control of objects and their dependencies from the
main program to a container or framework.
• The IoC container uses two primary mechanisms to work:
Bean instantiation:
• The IoC container is responsible for creating and configuring beans. This can be
done through XML configuration, Java annotations, or a combination of both.
Dependency injection:
• The IoC container injects dependencies into beans. This means that the IoC
container is responsible for providing beans with the objects they need to
function.
Spring Dependency Injection
• Dependency Injection (DI) is a design pattern that allows you to
decouple your code by making it easier to create and manage
objects.
• In Spring, DI is implemented using the Inversion of Control (IoC)
container. The IoC container is responsible for creating and managing
objects, and it injects them into your code when needed.
• Dependency Injection is a fundamental aspect of the Spring
framework, through which the Spring container “injects” objects into
other objects or “dependencies”.
There are two types of Spring Dependency Injection.
• Setter Dependency Injection (SDI)
• Constructor Dependency Injection (CDI)
Spring IoC (Inversion of Control) Spring Dependency Injection
Spring IoC Container is the core of Spring Spring Dependency injection is a way to inject the
Framework. It creates the objects, configures and dependency of a framework component by the
assembles their dependencies, manages their entire following ways of spring: Constructor Injection
life cycle. and Setter Injection
Spring helps in creating objects, managing objects, Spring framework helps in the creation of loosely-
configurations, etc. because of IoC (Inversion of coupled applications because of Dependency
Control). Injection.
IoC is a design principle where the control flow of Dependency Injection is one of the subtypes of the
the program is inverted. IOC principle.
4. Press finish
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.8</version>
</dependency>
10.
execute App.java
Aspect-Oriented Programming (AOP)
• Aspect-Oriented Programming (AOP) is a programming technique that allows developers
to modularize cross-cutting concerns. Cross-cutting concerns are tasks that affect
multiple parts of a program, such as logging, security, and transaction management.
• AOP allows developers to separate these concerns from the main program logic. This
makes the code more modular, reusable, and maintainable.
• Spring AOP is a popular implementation of AOP. It provides a simple and powerful way to
write custom aspects.
• Spring provides simple and powerful ways of writing custom aspects by using either
a schema-based approach or the @AspectJ annotation style. Both of these styles offer
fully typed advice and use of the AspectJ pointcut language while still using Spring AOP
for weaving.
• AOP is used in the Spring Framework to:
• Provide declarative enterprise services. The most important such service is declarative
transaction management.
• Let users implement custom aspects, complementing their use of OOP with AOP.
Benefits of using AOP
Modularity:
• AOP allows developers to separate cross-cutting concerns from the
main program logic. This makes the code more modular, reusable,
and maintainable.
Reusability:
• Aspects can be reused across multiple projects. This saves time and
effort, and it can help to improve the consistency of code.
Maintainability:
• AOP makes it easier to maintain code. This is because cross-cutting
concerns are separated from the main program logic. This makes it
easier to understand and modify the code.
WebSocket API
Spring Framework provides a WebSocket API that adapts to various
WebSocket engines, including Tomcat, Jetty, GlassFish, WebLogic, and
Undertow. This API allows developers to easily implement WebSocket-
based applications. The Spring Framework also provides a number of
features that make it easy to develop WebSocket-based applications,
including:
• A messaging framework that supports STOMP, a text-oriented
messaging protocol that can be used over any reliable 2-way
streaming network protocol such as TCP and WebSocket.
• A JavaScript client library that makes it easy to develop WebSocket-
based web applications.
• A number of pre-built WebSocket-based applications, such as a chat
application and a stock ticker.
BEAN SCOPE
• 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.
• In the Spring Framework, a bean's scope determines how long it lives and how many instances
of it are created.
• The default scope is 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.
• The prototype scope A new instance will be created for a single bean definition every time a
request is made for that bean. This is useful for beans that are not thread-safe or that need to be
customized for each request.
• The request scope creates a new instance of the bean for each HTTP request. This is useful for
beans that need to be associated with a specific request, such as a database connection or a
shopping cart.
• The session scope creates a new instance of the bean for each user session. This is useful for
beans that need to be associated with a specific user, such as a user profile or a shopping cart.
• The global session scope creates a new instance of the bean for each user session across all
applications in the same cluster. This is useful for beans that need to be shared across multiple
applications, such as a user profile or a shopping cart.
BEAN SCOPE
• You can specify the scope of a bean using the @Scope annotation. For
example, the following code creates a bean with the prototype scope:
@Scope("prototype")
public class MyBean {
// ...
}
OR
Autodetect(deprec
The autodetect mode uses two other modes for autowiring – constructor and byType.
ated in Spring 3)
1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default mode used
by Spring.
2. byName
It uses the name of the bean for injecting dependencies. However, it requires that the name of the property
and bean must be the same. It invokes the setter method internally for autowiring.
3. byType
It injects the dependency according to the type of the bean. It looks up in the configuration file for the class
type of the property. If it finds a bean that matches, it injects the property. If not, the program throws an
error. The names of the property and bean can be different in this case. It invokes the setter method
internally for autowiring.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>
4. constructor
It injects the required dependencies by invoking the constructor. It works similar to the “byType” mode but it looks for the
class type of the constructor arguments. If none or more than one bean are detected, then it throws an error, otherwise, it
autowires the “byType” on all constructor arguments.
5. autodetect
The autodetect mode uses two other modes for autowiring – constructor and byType. It first tries to autowire via the
constructor mode and if it fails, it uses the byType mode for autowiring. It works in Spring 2.0 and 2.5 but is deprecated
from Spring 3.0 onwards.
2. On a constructor: You can also use the @Autowired annotation on a constructor. This will cause Spring to inject an
instance of the dependency into the constructor when the bean is created.
public class MyBean {
private MyDependency dependency;
@Autowired
public MyBean(MyDependency dependency) {
this.dependency = dependency;
}
}
3. On a setter method: You can also use the @Autowired annotation on a setter method. This will cause Spring to
inject an instance of the dependency into the setter method when the bean is created.
The @Autowired annotation can be used on any field, constructor, or setter method that is declared in a Spring
bean. The dependency that is injected must be a Spring bean itself.
Life Cycle Call backs
• 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.
Example: Life Cycle Call Back
Spring BOOT
Using REST API
ABES Engineering College, Ghaziabad
Introduction
• Spring Boot is a project that is built on 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 used to create a
stand-alone Spring-based application that you can just run because it
needs minimal Spring configuration.
As summarized in the below figure, Spring Boot is
the combination of Spring Framework and
Embedded Servers.
Spring Boot Architecture
• Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc.
The architecture of Spring Boot is the same as the architecture of Spring MVC,
except for one thing: there is no need for DAO and DAOImpl classes in Spring
boot. As a summary, in a simple spring boot flow:
• Data access layer gets created and CRUD operations are performed.
• The client makes the HTTP requests.
• The request goes to the controller, and the controller maps that request and
handles it. After that, it calls the service logic if required.
• In the service layer, all the business logic performs. It performs the logic on
the data that is mapped to JPA with model classes.
• A response page is returned to the user if no error occurs.
•
Spring Boot Architecture
Properties file
•
Spring Boot run() method
•
Spring Boot resources folder
•
Spring Boot Normal Application “pom.xml”
•
Spring Boot Web Application “pom.xml”
•
Spring Boot Runners
• In Spring Boot, runners are components used to execute code when
the application is started. They are typically implemented using
Spring's ApplicationRunner or CommandLineRunner interfaces. These
runners allow you to perform tasks such as database initialization,
data loading, or any custom startup logic.
Application Runner
• The
ApplicationRunner
interface in Spring
Boot provides a way
to execute code
after the
application context
is initialized and
before Spring Boot
starts servicing
incoming requests
CommandLine Runner
• Similar to
ApplicationRunner, import org.springframework.boot.CommandLineRunner;
CommandLineRunn import org.springframework.stereotype.Component;
er is an alternative
interface that @Component
provides a run public class MyCommandLineRunner implements
method with an CommandLineRunner {
array of String
arguments. These @Override
arguments are public void run(String... args) throws Exception {
passed directly to // Code to execute on application startup
the application System.out.println("CommandLineRunner is running...");
when it is started }
from the command }
line.
Springboot Logger
• 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.
Restful Web Services
• 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). For example:
• The resource has representations like XML, HTML, and JSON. The current state capture by
representational resource. When we request a resource, we provide the representation of
the resource.
Restful Web Services
Create a new package as com.example.demo.controller and create a new class as SampleController , now
make this class as RestController using @RestController annotation
Now, Apply @GetMapping annotation to create an end point to access this controller, given below is
code:
2. PostMapping
3. Spring – Request Body
• @RequestBody: Annotation is used to get the request body in
the incoming request.
4. Spring – Request Mapping and
ResponseBody
• @RequestMapping Annotation which is used to map HTTP requests to handler
methods of MVC and REST controllers.
• The @RequestMapping annotation can be applied to class-level and/or method-
level in a controller.
• The class-level annotation maps a specific request path or pattern onto a controller.
• You can then apply additional method-level annotations to make mappings more
specific to handler methods.
• @ResponseBody annotation tells a controller that the object returned is
automatically serialized into JSON and passed back into the HttpResponse object.
When you use the @ResponseBody annotation on a method, Spring converts the
return value and writes it to the HTTP response automatically.
5. Spring – Request Mapping and ResponseBody
6. Spring – PathVariable
• The @PathVariable annotation is used to extract the value from the URI. It is
most suitable for the RESTful web service where the URL contains some
value. Spring MVC allows us to use multiple @PathVariable annotations in the
same method. A path variable is a critical part of creating rest resources.
@GetMapping(path="/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name)
{
return new HelloWorldBean(String.format("Hello World, %s", name));
}
URL: http://localhost:8080/hello-world/path-variable/ABES O/P- {“message”:”Hello World,
ABES”}
7. Spring – Request Parameter
• The @RequestParam annotation is used to extract data from the
query parameters in the request URL. Query parameters are the key-
value pairs that appear after the ? in a URL.
Rest API