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

Unit-5

Spring Core is a fundamental part of the Spring Framework, providing the essential features
for dependency injection (DI) and aspect-oriented programming (AOP). Here are some of the
core basics of Spring Core:

1. Dependency Injection (DI)

 Definition: DI is a design pattern used to implement IoC (Inversion of Control),


allowing the Spring container to manage the dependencies of objects.
 Types of DI:
o Constructor Injection: Dependencies are provided through a constructor.
o Setter Injection: Dependencies are provided through setter methods.
o Field Injection: Dependencies are directly injected into fields (not
recommended due to issues with immutability and testability).

2. Inversion of Control (IoC) Container

 Definition: The IoC container is responsible for instantiating, configuring, and


assembling the objects (beans) in your application.
 Types of IoC Containers:
o BeanFactory: The simplest container providing basic DI support.
o ApplicationContext: A more advanced container providing additional features
like event propagation, declarative mechanisms to create a bean, and more.

3. Bean Configuration

 XML Configuration: Beans are defined in an XML file.


 Java-based Configuration: Beans are configured using @Configuration classes and
@Bean methods.
 Annotation-based Configuration: Beans are configured using annotations like
@Component, @Service, @Repository, and @Controller.

4. Bean Lifecycle

 Initialization: Beans are created and dependencies are injected.


 Post-Initialization: Custom initialization methods can be specified using
@PostConstruct or init-method in XML.
 Destruction: Custom destroy methods can be specified using @PreDestroy or
destroy-method in XML.

5. Aspect-Oriented Programming (AOP)

 Definition: AOP is a programming paradigm that allows you to separate cross-cutting


concerns (e.g., logging, security) from business logic.
 Key Concepts:
o Aspect: A module that encapsulates a concern.
o Join Point: A point during execution (e.g., method execution) where an aspect
can be applied.
o Advice: Action taken by an aspect at a particular join point.
o Pointcut: A predicate that matches join points.
o Weaving: Process of linking aspects with other application types.

6. Spring Beans

 Definition: Objects that form the backbone of a Spring application and are managed
by the Spring IoC container.
 Scope of Beans:
o Singleton: A single instance per Spring container (default scope).
o Prototype: A new instance every time a bean is requested.
o Request: A single instance per HTTP request (for web applications).
o Session: A single instance per HTTP session (for web applications).
o Global Session: A single instance per global HTTP session (for web
applications, rarely used).

7. Spring Context and Spring Expression Language (SpEL)

 Spring Context: Provides access to configuration information and application


services.
 SpEL: A powerful expression language that supports querying and manipulating an
object graph at runtime.

Example: Basic Spring Configuration

XML Configuration

xml
Copy code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="myBean" class="com.example.MyBean">


<property name="property" value="value"/>
</bean>
</beans>

Java-based Configuration

java
Copy code
@Configuration
public class AppConfig {

@Bean
public MyBean myBean() {
return new MyBean("value");
}
}

Annotation-based Configuration

java
Copy code
@Component
public class MyBean {

private String property;

@Autowired
public MyBean(@Value("value") String property) {
this.property = property;
}
}

Spring Dependency Injection:

Dependency Injection is the main functionality provided by Spring IOC (Inversion of


Control). The Spring-Core module is responsible for injecting dependencies through either
Constructor or Setter methods. The design principle of Inversion of Control emphasizes
keeping the Java classes independent of each other and the container frees them from
object creation and maintenance. These classes, managed by Spring, must adhere to the
standard definition of Java-Bean. Dependency Injection in Spring also ensures loose-
coupling between the classes.

Need for Dependency Injection:


Suppose class One needs the object of class Two to instantiate or operate a method, then
class One is said to be dependent on class Two. Now though it might appear okay to
depend a module on the other but, in the real world, this could lead to a lot of problems,
including system failure. Hence such dependencies need to be avoided.

Types of Spring Dependency Injection:

There are two types of Spring Dependency Injection. They are:

1. Setter Dependency Injection (SDI): This is the simpler of the two DI methods. In this,
the DI will be injected with the help of setter and/or getter methods. Now to set the DI
as SDI in the bean, it is done through the bean-configuration file For this, the property
to be set with the SDI is declared under the <property> tag in the bean-config file.

2. Constructor Dependency Injection (CDI): In this, the DI will be injected with the
help of contructors. Now to set the DI as CDI in bean, it is done through the bean-
configuration file For this, the property to be set with the CDI is declared under
the <constructor-arg> tag in the bean-config file
Spring Dependency Injection (DI) in Java can be implemented in three main ways: using
annotations, XML configuration, and Java-based configuration.

1. Annotation-Based Configuration

Spring annotations allow for more concise and readable configuration by using Java
annotations.

Steps:

1. Define the Bean: Annotate your class with @Component, @Service, @Repository, or
@Controller to indicate that it is a Spring-managed bean.
2. Inject Dependencies: Use the @Autowired annotation on constructors, methods, or
fields to inject dependencies.

2. Java-Based Configuration

Java-based configuration provides a type-safe and flexible way to configure your beans.

Steps:

1. Create a Configuration Class: Annotate a class with @Configuration to indicate that


it contains bean definitions.
2. Define Beans: Use the @Bean annotation to define beans and their dependencies.

Key Points

 Annotation-Based Configuration:
o Use annotations like @Component, @Autowired, @Service, @Repository, and
@Controller.
o @ComponentScan in the configuration class scans the specified package for
Spring components.
 Java-Based Configuration:
o Define beans using the @Bean annotation within a @Configuration class.
o Method names used in @Bean annotations usually serve as bean IDs.
Spring IoC (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. 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 IoC (Inversion of Control) Spring Dependency Injection

Spring IoC Container is the core of Spring Spring Dependency injection is a way to
Framework. It creates the objects, inject the dependency of a framework
configures and assembles their component by the following ways of
dependencies, manages their entire life spring: Constructor Injection and Setter
cycle. Injection

Spring helps in creating objects, managing Spring framework helps in the creation of
objects, configurations, etc. because of IoC loosely-coupled applications because of
(Inversion of Control). Dependency Injection.

Dependency Injection is the method of


Spring IoC is achieved through providing the dependencies and Inversion
Dependency Injection. of Control is the end result of Dependency
Injection.

IoC is a design principle where the control Dependency Injection is one of the
flow of the program is inverted. subtypes of the IOC principle.

Aspect-Oriented Programming is one way In case of any changes in business


to implement Inversion of Control. requirements, no code change is required.
AOP

Aspect-Oriented Programming (AOP) in Spring is a powerful feature that allows the


separation of cross-cutting concerns (such as logging, security, transaction management, etc.)
from the main business logic. By using AOP, you can encapsulate these concerns into
reusable aspects, which can then be applied across different parts of an application without
modifying the code.

Key Concepts of AOP

1. Aspect:
o An aspect is a module that encapsulates a cross-cutting concern. Aspects can
contain both what to do and when to do it.
2. Join Point:
o A join point is a specific point in the program execution, such as the execution
of a method or handling of an exception.
3. Advice:
o Advice is the action taken by an aspect at a particular join point. Spring supports
different types of advice:
 Before: Executed before a join point.
 After: Executed after a join point, regardless of its outcome.
 After Returning: Executed after a join point completes normally.
 After Throwing: Executed if a method exits by throwing an exception.
 Around: Surrounds a join point, allowing the advice to perform custom
behavior before and after method invocation.
4. Pointcut:
o A pointcut is an expression that matches join points. It defines where an advice
should be applied.
5. Weaving:
o Weaving is the process of linking aspects with other application types or objects
to create an advised object. It can be done at compile time, load time, or
runtime.

Bean Scopes-

In Spring, the scope of a bean defines the lifecycle and visibility of that bean in the Spring
context. There are several scopes available in Spring, each serving different use cases. Here’s
a detailed overview of the common bean scopes in Spring:

Common Bean Scopes

1. Singleton
2. Prototype
3. Request
4. Session
5. Global Session
6. Application
7. WebSocket
1. Singleton

 Definition: This is the default scope in Spring. Only one instance of the bean is
created per Spring IoC container.
 Usage: Used when you want to share a single instance of a bean across the entire
application context.

The singleton scope in Spring ensures that only one instance of a bean is created per
container, making it suitable for stateless services or shared resources. It is the default scope
and promotes efficient resource usage. Care must be taken to handle shared state
appropriately in multi-threaded environments.

If a scope is set to singleton, the Spring IoC container creates exactly one instance of the
object defined by that bean definition. This single instance is stored in a cache of such
singleton beans, and all subsequent requests and references for that named bean return the
cached object.

In Spring, the singleton scope is the default scope for beans. When a bean is defined with the
singleton scope, only one instance of that bean is created per Spring IoC container. This
single instance is shared across the entire application context and is typically used for
stateless services or shared resources.

Key Characteristics of Singleton Scope

1. Single Instance:
o Only one instance of the bean is created for the entire Spring container.
o All requests for this bean will return the same instance.
2. Eager Initialization:
o By default, singleton beans are eagerly initialized when the Spring container is
created, which means they are instantiated and their dependencies are injected
as soon as the container is initialized.
o Lazy initialization can be configured if needed using @Lazy.
3. Shared State:
o Singleton beans can maintain shared state between different parts of the
application. Care must be taken to ensure thread safety if the bean is accessed
by multiple threads simultaneously.

2. Prototype

 Definition: A new instance of the bean is created every time it is requested from the
Spring container.
 Usage: Used when you need a new instance of a bean each time it is used, such as
stateful beans.

If the scope is set to prototype, the Spring IoC container creates a new bean instance of
the object every time a request for that specific bean is made. As a rule, use the
prototype scope for all state-full beans and the singleton scope for stateless beans.
To define a prototype scope, you can set the scope property to prototype in the bean
configuration file
The prototype scope in Spring is used to create a new instance of a bean every time it
is requested. This is useful for stateful beans or beans that need to maintain their own
state independently. Unlike singleton beans, prototype beans are lazily initialized and
do not have automatic cleanup handled by the Spring container, so you must manage
their destruction manually if needed. Understanding and using the prototype scope
appropriately can help in designing applications with the required level of instance
independence.

In Spring, the prototype scope is used to create a new instance of a bean every time it is
requested from the Spring container. This is in contrast to the singleton scope, where only
one instance of the bean is created per Spring IoC container. The prototype scope is useful
for stateful beans or beans that need to maintain their own state independently.

Key Characteristics of Prototype Scope

1. Multiple Instances:
o A new instance of the bean is created every time it is requested from the
container.
o No shared instance is maintained.
2. Lazy Initialization:
o Prototype beans are not initialized until they are requested. This is different
from singleton beans, which are eagerly initialized by default.
3. No Automatic Cleanup:
o The Spring container does not manage the complete lifecycle of a prototype
bean, particularly in terms of destruction. You must handle the cleanup of
prototype beans manually if necessary.

3. Request

 Definition: A new instance of the bean is created for each HTTP request. This scope
is only valid in a web-aware Spring application context.
 Usage: Used for beans that are supposed to live and be used during a single HTTP
request.

In Spring, the request scope is used to create a new bean instance for each HTTP request.
This scope is only valid in a web-aware Spring application context. It is particularly useful
for beans that need to be stateful within the context of a single HTTP request but do not need
to maintain state between requests.

Key Characteristics of Request Scope

1. New Instance per Request:


o A new instance of the bean is created for each HTTP request.
o The instance is scoped to the lifecycle of a single HTTP request.
2. Web-Aware Context:
o The request scope is only available in web-aware Spring application contexts.
3. Automatic Cleanup:
o Beans in the request scope are automatically cleaned up by the container at the
end of the request.

The request scope in Spring is ideal for beans that need to be instantiated for each HTTP
request. This scope ensures that each request gets a fresh instance of the bean, making it
suitable for request-specific data or services. When using request-scoped beans in
conjunction with singleton beans, the Provider interface or ObjectFactory can be used to
manage the lifecycle differences and ensure that the request-scoped bean is properly handled.

4. Session

 Definition: A new instance of the bean is created for each HTTP session. This scope
is also only valid in a web-aware Spring application context.
 Usage: Used for beans that should maintain state across multiple HTTP requests
within the same session.

The request scope in Spring is ideal for beans that need to be instantiated for each HTTP
request. This scope ensures that each request gets a fresh instance of the bean, making it
suitable for request-specific data or services. When using request-scoped beans in
conjunction with singleton beans, the Provider interface or ObjectFactory can be used to
manage the lifecycle differences and ensure that the request-scoped bean is properly handled.

In Spring, the session scope is used to create a new bean instance for each HTTP session.
This scope is particularly useful for beans that need to maintain state across multiple HTTP
requests within a single user's session. The bean instance is created when the session starts
and is discarded when the session ends.

Key Characteristics of Session Scope

1. New Instance per Session:


o A new instance of the bean is created for each HTTP session.
o The instance is alive for the entire duration of the session.
2. Web-Aware Context:
o The session scope is only available in web-aware Spring application contexts
(e.g., Spring MVC).
3. Automatic Cleanup:
o Beans in the session scope are automatically cleaned up by the container when
the session expires or is invalidated.

5. Global Session

 Definition: A new instance of the bean is created for each global HTTP session. This
scope is typically only used in portlet-based web applications.
 Usage: Used for beans that should be shared across multiple sessions in a portlet
environment.
In Spring, the globalSession scope is used in a Portlet environment where you have a global
session across multiple portlets. It is specific to Portlet applications and is rarely used outside
this context. The globalSession scope allows you to have a bean that is scoped to the global
HTTP session, making it available to all portlets in the same web application.

Key Characteristics of Global Session Scope

1. Portlet-Specific:
o The globalSession scope is specific to Portlet applications.
o It is used to share a single bean instance across all portlets in a global HTTP
session.
2. New Instance per Global Session:
o A new instance of the bean is created for each global HTTP session.
o The instance is alive for the entire duration of the global session.
3. Web-Aware Context:
o The global session scope is only available in web-aware Spring application
contexts that support Portlet environments.
4. Automatic Cleanup:
o Beans in the global session scope are automatically cleaned up by the container
when the global session expires or is invalidated.

The globalSession scope in Spring is designed for use in Portlet environments, where it
allows you to create a bean that is scoped to the global HTTP session. This scope ensures
that a single instance of the bean is shared across all portlets in the same web application,
and it is automatically cleaned up when the global session expires or is invalidated. While
the globalSession scope is highly specific and not commonly used outside of Portlet
applications, it provides a valuable mechanism for sharing state across multiple portlets
within the same user session.

6. Application

 Definition: A new instance of the bean is created for the lifecycle of a ServletContext.
This scope is available only in a web-aware Spring application context.
 Usage: Used for beans that should be shared across all servlets in a ServletContext.

In Spring, the application scope is used to define a bean that is shared across the entire
Servlet context. This means that a single instance of the bean is created for the entire web
application, and it is available to all components and requests within that application. The
application scope is useful for sharing configuration settings, caching, or any other data that
needs to be globally accessible throughout the application.

Key Characteristics of Application Scope

1. Single Instance per Application:


o A single instance of the bean is created for the entire Servlet context.
o The instance is shared across all requests and sessions within the web
application.
2. Long Lifecycle:
oThe bean exists for the entire lifecycle of the web application.
o It is created when the application starts and destroyed when the application
stops.
3. Web-Aware Context:
o The application scope is only available in web-aware Spring application
contexts.
4. Automatic Cleanup:
o Beans in the application scope are automatically cleaned up by the container
when the application shuts down.

The application scope in Spring is ideal for beans that need to be shared across the entire
web application. This scope ensures that a single instance of the bean is available to all
requests, sessions, and components within the application, making it suitable for global
configuration, shared resources, or caching mechanisms. The application scoped bean is
created when the application starts and destroyed when the application stops, providing a
long lifecycle that matches the lifespan of the web application itself.

7. WebSocket

 Definition: A new instance of the bean is created for the lifecycle of a WebSocket
session. This scope is available only in a web-aware Spring application context that
supports WebSocket.
 Usage: Used for beans that should be created per WebSocket session.

In Spring, the WebSocket scope is used to manage the lifecycle of beans in the context of
WebSocket communication. Spring provides a framework for handling WebSocket
connections, messages, and events, allowing for full-duplex communication between client
and server.

Using WebSocket in Spring allows for real-time, full-duplex communication between clients
and servers. By configuring WebSocket endpoints, message brokers, and handlers, you can
easily set up a system to handle WebSocket messages and events. The combination of
Spring's WebSocket support and the STOMP protocol provides a powerful framework for
developing real-time web applications.

Key Concepts of WebSocket in Spring

1. WebSocket Handlers:
o Components that handle WebSocket messages, connection events, and
disconnection events.
2. Stomp Protocol:
o An optional higher-level messaging protocol over WebSocket that supports
broker-based messaging and subscriptions.
3. WebSocket Configuration:
o Spring configuration to register WebSocket endpoints and message brokers.
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.

Auto-wiring is a feature in Spring that allows the Spring container to automatically resolve
and inject collaborating beans into your bean. It minimizes the need for explicit
configuration and allows you to focus on the business logic rather than the wiring of
dependencies.

Key Concepts of Auto-Wiring

1. @Autowired Annotation:
o Used to mark a constructor, field, setter method, or configuration method as to
be autowired by Spring's dependency injection facilities.
2. @Qualifier Annotation:
o Used in conjunction with @Autowired to resolve ambiguity when multiple
beans of the same type exist.
3. Default Autowiring:
o Spring uses byType autowiring by default. If there is ambiguity, it will result in
an exception unless specifically resolved by @Qualifier.

Types of Autowiring Modes

1. No Autowiring (default):
o No autowiring. You must specify dependencies manually.
2. byType:
o Spring tries to match and wire a property by its type.
3. byName:
o Spring tries to match and wire a property by its name.
4. constructor:
o Similar to byType, but applies to constructor arguments.
5. autodetect:
o Spring first tries to autowire by constructor, and if it doesn’t work, it tries
byType.

Auto-wiring in Spring simplifies dependency management by automatically injecting the


required beans, reducing the need for explicit configuration. With annotations like
@Autowired and @Qualifier, Spring makes it easy to handle dependency injection, even in
complex scenarios with multiple implementations.
No. Mode Description

1) no It is the default autowiring mode. It means no autowiring bydefault.

2) byName The byName mode injects the object dependency according to name of the
bean. In such case, property name and bean name must be same. It internally
calls setter method.

3) byType The byType mode injects the object dependency according to type. So
property name and bean name can be different. It internally calls setter
method.

4) constructor The constructor mode injects the dependency by calling the constructor of the
class. It calls the constructor having large number of parameters.

5) autodetect It is deprecated since Spring 3.

Spring Annotation:-
Spring annotations provide a powerful way to configure and manage your Spring
applications declaratively. By leveraging these annotations, you can reduce boilerplate code,
improve readability, and maintain a clear separation of concerns in your application.

Annotations in Spring are a powerful way to configure your Spring application. They
provide a declarative approach to defining bean dependencies, lifecycle methods, and
configuration settings, making your code more readable and easier to manage. Below is an
overview of some of the key annotations used in Spring.

Core Spring Annotations

1. @Component, @Service, @Repository, and @Controller

These annotations are used to mark classes as Spring-managed beans. They are
specializations of the @Component annotation and are used for different layers in an
application:

 @Component: Generic stereotype for any Spring-managed component.


 @Service: Indicates that an annotated class is a service, typically used in the service
layer.
 @Repository: Indicates that an annotated class is a DAO (Data Access Object), and it
also enables exception translation.
 @Controller: Indicates that an annotated class is a controller (typically used in Spring
MVC).

2. @Autowired

Used to inject dependencies automatically by type.


3. @Qualifier

Used in conjunction with @Autowired to resolve ambiguity when multiple beans of the same
type exist.

4. @Value

Used to inject values into fields, methods, and constructor arguments from a property file.

5. @Configuration and @Bean

 @Configuration: Indicates that a class declares one or more @Bean methods and
may be processed by the Spring container to generate bean definitions and service
requests for those beans at runtime.
 @Bean: Indicates that a method produces a bean to be managed by the Spring
container.

6. @Scope

Defines the scope of a bean (e.g., singleton, prototype, request, session).

Spring MVC Annotations

1. @RequestMapping

Used to map web requests to specific handler classes and/or handler methods.

2. @RestController

A convenience annotation that combines @Controller and @ResponseBody. It eliminates the


need to annotate each method with @ResponseBody.

3. @RequestParam and @PathVariable

 @RequestParam: Binds a web request parameter to a method parameter.


 @PathVariable: Binds a URI template variable to a method parameter

4. @ModelAttribute

Used to bind a method parameter or method return value to a named model attribute and then
expose it to a web view.
Life Cycle call back:

In Spring, beans go through a lifecycle that includes several phases, from their creation to
their destruction. Spring provides various lifecycle callbacks that allow you to hook into
these phases and perform custom actions at specific points. These callbacks can be defined
using annotations, implementing specific interfaces, or using XML configuration.

Key Lifecycle Callbacks

1. InitializingBean and DisposableBean Interfaces


2. @PostConstruct and @PreDestroy Annotations
3. Custom Init and Destroy Methods
4. BeanPostProcessor Interface
5. SmartLifecycle Interface

1. InitializingBean and DisposableBean Interfaces

 InitializingBean: Contains a afterPropertiesSet method that is called after the bean's


properties have been set.
 DisposableBean: Contains a destroy method that is called before the bean is
destroyed.

2. @PostConstruct and @PreDestroy Annotations

 @PostConstruct: Annotate a method to be called after the bean's properties have been
set.
 @PreDestroy: Annotate a method to be called before the bean is destroyed.

3. Custom Init and Destroy Methods

Define custom initialization and destruction methods using XML configuration or the
@Bean annotation in a @Configuration class.

4. BeanPostProcessor Interface

 BeanPostProcessor: Allows you to perform operations before and after the


initialization of beans. It has two methods: postProcessBeforeInitialization and
postProcessAfterInitialization.

5. SmartLifecycle Interface

 SmartLifecycle: A more advanced lifecycle interface that extends Lifecycle and


provides additional methods for more control over the startup and shutdown phases of
a bean. It includes start, stop, isRunning, and isAutoStartup methods.

Spring provides several ways to manage the lifecycle of beans, from initialization to
destruction. By using interfaces like InitializingBean and DisposableBean, annotations like
@PostConstruct and @PreDestroy, custom init and destroy methods, BeanPostProcessor,
and SmartLifecycle, you can hook into the lifecycle events of your beans and perform
custom actions as needed. These tools give you fine-grained control over how and when your
beans are initialized and cleaned up, ensuring your application runs smoothly.
Bean Configuration style:

Spring provides multiple ways to configure beans in an application. The main styles of bean
configuration are:

1. XML Configuration
2. Java-based Configuration (using @Configuration and @Bean annotations)
3. Annotation-based Configuration (using stereotype annotations like
@Component, @Service, @Repository, and @Controller)

1. XML Configuration

This is the traditional way of configuring beans in Spring. You define the beans and their
dependencies in an XML file.

2. Java-based Configuration

This style uses @Configuration classes and @Bean methods to define beans.

3. Annotation-based Configuration

This style uses stereotype annotations (@Component, @Service, @Repository, @Controller)


to define beans and @Autowired for dependency injection.

Spring provides multiple styles for configuring beans, allowing you to choose the one that
best fits your needs. XML configuration offers a traditional approach, while Java-based
configuration provides a type-safe and IDE-friendly way to configure beans. Annotation-
based configuration leverages the power of annotations to minimize configuration and focus
on business logic. Each approach has its advantages and can be used individually or in
combination to create flexible and maintainable Spring applications.
Spring Boot:

Spring Boot is an extension of the Spring framework that simplifies the setup and
development of new Spring applications. It provides a wide range of out-of-the-box
configurations to help you get your application up and running quickly, without needing
extensive setup.

Key Features of Spring Boot

1. Auto-Configuration
2. Standalone Applications
3. Embedded Servers
4. Production-Ready Features
5. Spring Boot Starters
6. Spring Boot Actuator
7. Easy Dependency Management
1. Auto-Configuration

Spring Boot's auto-configuration feature automatically configures your Spring application


based on the dependencies present in the classpath. This reduces the need for explicit
configuration in your application.properties or application.yml files.

2. Standalone Applications

Spring Boot allows you to create standalone applications that can be run from the command
line. You don't need to deploy your application to an external application server. This is
achieved through the public static void main(String[] args) method and the
SpringApplication.run() method.

3. Embedded Servers

Spring Boot includes embedded servers such as Tomcat, Jetty, and Undertow. This means
you can package your application along with an embedded server into a single executable
JAR file, simplifying deployment.

4. Production-Ready Features

Spring Boot includes several production-ready features like metrics, health checks, and
externalized configuration. These features are provided by Spring Boot Actuator.

5. Spring Boot Starters

Spring Boot starters are a set of convenient dependency descriptors you can include in your
application to get all the necessary dependencies and auto-configuration settings. For
example, spring-boot-starter-web includes all dependencies required to create a web
application using Spring MVC.

6. Spring Boot Actuator

Spring Boot Actuator provides production-ready features to help you monitor and manage
your application. It includes endpoints for metrics, health checks, and other information.

7. Easy Dependency Management

Spring Boot simplifies dependency management with the help of the Spring Boot Starter
Parent POM, which includes default versions of commonly used libraries.

Spring Boot simplifies the process of developing Spring applications by providing auto-
configuration, embedded servers, and production-ready features. It allows you to create
standalone, production-grade applications with minimal setup, leveraging the power of the
Spring ecosystem. Spring Boot's starters and Actuator make it easier to manage
dependencies and monitor your application, respectively.
Spring Boot Runners:

Spring Boot runners (CommandLineRunner and ApplicationRunner) are useful for executing
code after the application context has been initialized. They provide a way to run specific
logic during the startup of a Spring Boot application, such as initializing data, checking
configurations, or starting background tasks. By implementing these interfaces and using
annotations like @Component and @Order, you can control the execution order and
behavior of these runners in your application.

In Spring Boot, runners are components that allow you to run specific code when the
application starts. There are two main types of runners:

1. CommandLineRunner
2. ApplicationRunner

Both runners are functional interfaces that you can implement to execute code after the
Spring Boot application context has been loaded.

Restful Web service:

Spring Boot simplifies the development of RESTful web services by providing auto-
configuration, embedded servers, and various starter projects. With the above steps, you can
set up a basic RESTful web service, define models, repositories, services, and controllers,
and configure your application for development.

Rest Controller:

In Spring Boot, a REST controller is a specialized version of the controller that is used to
create RESTful web services. It is marked with the @RestController annotation, which is a
convenience annotation that combines @Controller and @ResponseBody.

Key Annotations

 @RestController: Marks the class as a RESTful web service controller.


 @RequestMapping: Maps HTTP requests to handler methods of MVC and REST
controllers.
 @GetMapping: Shortcut for @RequestMapping(method = RequestMethod.GET).
 @PostMapping: Shortcut for @RequestMapping(method = RequestMethod.POST).
 @PutMapping: Shortcut for @RequestMapping(method = RequestMethod.PUT).
 @DeleteMapping: Shortcut for @RequestMapping(method =
RequestMethod.DELETE).
 @PathVariable: Used to extract values from the URI.
 @RequestBody: Indicates that a method parameter should be bound to the body of
the HTTP request.
 @ResponseEntity: Used to represent the entire HTTP response, including status code,
headers, and body.
Path Variable;

In the context of a Spring application in Java, the path variable or @PathVariable annotation
is used in Spring MVC to handle dynamic parts of the URI (Uniform Resource Identifier). It
allows you to extract values from the URI and pass them as parameters to a method in a
controller class.

The @PathVariable annotation is a powerful feature in Spring MVC that allows you to
extract values from the URI and use them as method parameters in your controller classes. It
helps in creating RESTful web services by enabling dynamic URL patterns and making your
web application more flexible and user-friendly.

API’s in Spring:

In a Spring MVC or Spring Boot application, you can create RESTful APIs that handle
different HTTP methods such as GET, POST, PUT, and DELETE. Each of these methods
serves a different purpose in REST architecture:

 GET: Retrieves data from the server.


 POST: Sends new data to the server.
 PUT: Updates existing data on the server.
 DELETE: Deletes data from the server.

You might also like