You are on page 1of 51

Introducing Spring & Spring Boot

Advantages of Spring Framework


Advantages of Spring Framework
 Lightweight
 Loosely coupled using dependency injection.
 Provides pre-defined templates for JDBC,
Hibernate, JPA, etc. and good integration with
other frameworks.
 Thanks to Dependency Injection, these
applications are easy to test.
Advantages of Spring Framework...
 Offers powerful abstraction to Java EE
specifications such as JMS, JDBC, JPA, and
JTA.
 Provides declarative support for caching,
validation, transactions, and formatting.
 Offers flexibility to configure beans in multiple
ways such as XML, Annotations, and
JavaConfig.
 Reduces Duplication of code.
Spring Ecosystem
Spring Ecosystem...
Spring Ecosystem can be split into five parts
 Web layer
 Common layer
 Service layer
 Data layer
 Foundation layer (Spans across all above layers)
 Each layer comprises of a list of Spring projects as depicted
in the above image.
 In this course, you will dive deep into Spring Boot after a
quick walk through on the basics of Spring framework.
What is Spring Bean?

 Beans are objects that form the pivotal part of


your application. They are instantiated,
assembled, and managed by the Spring IoC
container.
 The beans are built with configuration metadata
that are provided to the container. This
configuration data determines the bean
behavior.
Configuring Spring Bean
 The following three techniques offer
configuration metadata to Spring Container.
1. XML based configuration file
2. Annotation-based configuration
3. Java-based configuration
 Spring IoC container is completely decoupled
from the format where configuration metadata
is written.
Bean Scopes
 While defining a bean you can declare a scope
for the bean.
E.g., to force Spring to create a new bean
instance every time, you must declare the scope
attribute of the bean to be prototype.
If you require Spring to return the same bean
instance every time, you must declare the scope
attribute of the bean to be singleton.
Bean Scopes...
 There are five types of Scopes defined

1.singleton
2.prototype
3.request
4.session
5.global-session
Bean - Lifecycle
Spring Bean - Lifecycle...
Initialization and Destruction Callbacks
 Callback methods are used to add user-defined
initialization and finalization tasks during the
Spring Bean Lifecycle.

 The two callback methods are

1.Initialization callbacks
2.Destruction callbacks
Initialization Callbacks
 You can implement the InitializingBean
interface and initialization work can be done
inside afterPropertiesSet() method as follows −
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
Destruction Callbacks
 You can implement DisposableBean interface
and finalization work can be done inside
destroy() method as follows −

public class ExampleBean implements DisposableBean {


public void destroy() {
// do some destruction work
}
}
Dependency Injection
 Dependency Injection is a fundamental aspect
of the Spring framework, through which the
Spring container “injects” objects into other
objects or “dependencies”. Simply put, this
allows for loose coupling of components and
moves the responsibility of managing
components onto the container.
Spring Boot
 Spring Boot allows you to build stand-alone,
operating, production-grade Spring based
Applications with ease.
 Spring Boot Framework
->is an opinionated framework
->is based on convention over configuration
->can build stand-alone applications
->can create production ready package
->has Embedded Tomcat server
Spring Boot...
 To summarize, Spring Boot Framework is a
pre-configured, pre-sugared set of
technologies/framework to minimize boiler
plate configuration offering the quickest way to
get a Spring web application ready and
operational with minimal configuration/coding
out-of-the-box.
Spring vs Spring Boot
 Diagram:
Spring Vs Spring Boot...
 In Spring, all configurations are manually done
by a developer, whereas configurations are
automatically done in Spring Boot.
Annotations
 The @RequestMapping annotation offers
“routing” details. It instructs Spring that any
HTTP request with “/” path must be mapped to
the home method.

 The @RestController annotation instructs


Spring to render the resulting string back to the
caller directly.
Annotations...
 @EnableAutoConfiguration annotation
instructs Spring Boot to “guess” how to
configure Spring, on the basis of added jar
dependencies. Since spring-boot-starter-web
added Spring MVC and Tomcat, the auto-
configuration will think that you are building a
web application and setting up Spring
subsequently.
Executable jars and Java
 Spring Boot does it differently and directly lets
you nest jars.
 The spring-boot-loader modules lets Spring
Boot to support executable war and jar files. If
you employ the Gradle or Maven plugin,
executable jars are created automatically, and
you do not have to know how they work.
Creating Self-Contained Executables
<dependencies>
<dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</dependency>
</dependencies>
Creating Self-Contained Executables...
 This section is added to pom.xml that includes
the maven plugin does the job of creating an
executable.
 If you search in the target directory, you must
see myproject-0.0.1-SNAPSHOT.jar. Running
an executable jar:

$ java -jar target/<<myproject>>-0.0.1-


SNAPSHOT.jar
Default Package
 Using default package must be avoided.

 It can result in certain problems for Spring Boot


applications that utilize
@SpringBootApplication, @EntityScan or
@ComponentScan annotations because every
class from each jar will be read.
Spring Boot Starters
 Dependency management is a critical part of a
complex project.
 And it consumes a lot of time performing this
manually.
 Spring Boot starters were developed to discuss
this issue. Starter POMs are a set of easy
dependency descriptors that you can add in your
application.
Spring Boot Starter Web
 Dependencies added automatically can be
classified into
 Spring
 core, beans, context, app
 Web MVC - Spring MVC
 Jackson - for Json Binding
 Validation - Hibernate Validator, Validation API
 Embedded Servlet Container - Tomcat
 Logging - logback, slf4j
Why Auto Configuration?
 Spring based applications have a lot of configurations to be
added.
For example,
 To use Spring MVC, we have to configure a component
scan, the dispatcher servlet, a view resolver, web JARs (for
delivering static content) and so on.
 To use Hibernate/JPA, we would have to configure a data
source, a transaction manager, an entity manager factory,
etc.
 This brings in a huge overhead to the developers working
on a complex application.
Auto Configuration...
 All auto configuration logic is executed in spring-boot-
autoconfigure.jar. All auto configuration logic for MVC,
JMS, data, and other frameworks is available in a JAR.

Auto-configuration @Conditional

 If specific classes are offered in the classpath, then the


configuration for that feature is enabled via auto
configuration. Annotations such as
@ConditionalOnMissingBean, @ConditionalOnClass, help
in providing these functions.
Running From an IDE
 You can import your project in your IDE and
run the same as a Simple Java Application.

Let us consider Eclipse IDE.

Steps

Click on File menu --> Import --> Existing


Maven Projects
Spring MVC
Building Spring MVC App
 Here is the list of http methods:

 Http method : Url suffix : Description


Get : /Category : Get all the Categories
Get : /Category/Id : Get the particular Category
Post : /Category : Create new Category
Put : /Category/Id : Update a category
Delete : /Category/Id : Deletes the Category
Microservices
 Microservices - also known as the microservice
architecture - is an architectural style that
structures an application as a collection of
services that are

 Highly maintainable and testable


 Loosely coupled
 Independently deployable
 Organized around business capabilities
 Owned by a small team
Microservices...
 Diagram:
Microservices Reference
 https://dzone.com/articles/spring-boot-
microservices-building-microservices-a
Spring Cloud Microservices Architecture
 In a system with a microservices architecture, there are a large number
of small-sized microservices that communicate with each other:

 Each of these microservices needs to execute across multiple


environments. In a given environment, there could be multiple
instances of that microservice running. This means the operations
team needs to manage a lot of configuration information for each
microservice.
Service Registration/Discovery
 The service registry is a key part of service discovery. It is
a database containing the network locations of service
instances. A service registry needs to be highly available
and up to date. Clients can cache network locations
obtained from the service registry. However, that
information eventually becomes out of date and clients
become unable to discover service instances. Consequently,
a service registry consists of a cluster of servers that use a
replication protocol to maintain consistency.
Service Registration/Discovery...
 Netflix Eureka is good example of a service registry. It
provides a REST API for registering and querying service
instances. A service instance registers its network location
using a POST request. Every 30 seconds it must refresh its
registration using a PUT request. A registration is removed
by either using an HTTP DELETE request or by the
instance registration timing out. As you might expect, a
client can retrieve the registered service instances by using
an HTTP GET request.
API Gateway
 An API gateway is an API management tool
that sits between a client and a collection of
backend services. An API gateway acts as a
reverse proxy to accept all application
programming interface (API) calls, aggregate
the various services required to fulfill them, and
return the appropriate result.
API Gateway...
 Diagram:
Dynamic Routing
 Dynamic routing uses multiple algorithms and
protocols. The most popular are Routing
Information Protocol (RIP) and Open Shortest
Path First (OSPF). Dynamic routing protocols
allow routers to share information about the
network with other routers to allow them to
select the best path to reach a destination.
Dynamic Routing...
 Diagram
Eureka Server
 Eureka Server is an application that holds the
information about all client-service
applications. Every Micro service will register
into the Eureka server and Eureka server knows
all the client applications running on each port
and IP address. Eureka Server is also known as
Discovery Server
Eureka Server...
 Diagram
Load Balancing
 Load balancing is defined as the methodical and
efficient distribution of network or application
traffic across multiple servers in a server farm.
Each load balancer sits between client devices
and backend servers, receiving and then
distributing incoming requests to any available
server capable of fulfilling them.
Load Balancing...
 Diagram:
Load Balancing...
 Round robin load balancing is a simple way to
distribute client requests across a group of
servers. A client request is forwarded to each
server in turn. The algorithm instructs the load
balancer to go back to the top of the list and
repeats again.
Load Balancing...
 Diagram:
Load Balancing...
 Diagram:
Circuit Breaker
 The Circuit Breaker pattern is usually described
in terms of network coupling. To protect the
system against transient failures of
subcomponent services, Circuit Breakers
decouple those that are suffering delays or
timeouts to prevent cascade failures.
Circuit Breaker...
 Diagram

You might also like