YDP_API&MS_UNIT_II[1]
YDP_API&MS_UNIT_II[1]
MICROSERVICES
UNIT II
Y DURGA PRASAD
Associate Professor
Department of Computer Science and Engineering
ADITYA
SPRING BOOT
Spring Boot is a framework built on top of the Spring framework that helps the developers to build Spring-based
applications very quickly and easily. The main goal of Spring Boot is to create Spring-based applications quickly
without demanding developers to write the boilerplate configuration.
It works because of the following reasons,
1. Spring Boot is an opinionated framework
Spring Boot forms opinions. It means that Spring Boot has some sensible defaults which you can use to quickly
build your application. For example, Spring Boot uses embedded Tomcat as the default web container.
2. Spring Boot is customizable
Though Spring Boot has its defaults, you can easily customize it at any time during your development based on
your needs. For example, if you prefer log4j for logging over Spring Boot built-in logging support then you can
easily make a dependency change in your pom.xml file to replace the default logger with log4j dependencies.
The main Spring Boot features are as follows:
Starter Dependencies Spring Boot Actuator
Automatic Configuration Easy-to-use Embedded Servlet Container Support2
ADITYA
There are multiple approaches to create a Spring Boot application. You can use any of the following approaches to
create the application:
❑Using Spring Boot CLI
❑Using Spring Initializr
❑Using the Spring Tool Suite (STS)
Understanding Spring Boot project structure
➢pom.xml
This file contains information about the project and configuration details used by Maven to build the
project.
➢application.properties
This file contains application-wide properties. To configure your application Spring reads the properties
defined in this file. In this file, you can define a server’s default port, the server’s context path, database
URLs, etc.
➢ DemoSpringBootApplication.java
It is annotated with @SpringBootApplication annotation which triggers auto-configuration and
component scanning and can be used to declare one or more @Bean methods also. It contains the main
method which bootstraps the application by calling the run() method on the SpringApplication class. The run
method accepts DemoSpringBootApplication.class as a parameter to tell Spring Boot that this is the primary
component.
➢DemoSpringBootApplicationTest.java
In this file test cases are written. This class is by default generated by Spring Boot to bootstrap Spring
application. 3
ADITYA
Spring Boot Starters
Spring Boot starters are pre-configured dependency descriptors with the most commonly used libraries that you can
add to your application. So you don't need to search for compatible libraries and configure them manually. Spring
Boot will ensure that the necessary libraries are added to the build. To use these starters, you have to add them to
the pom.xml file.
Some popular starters
❑spring-boot-starter - This is the core starter that includes support for auto-configuration, logging, and YAML.
❑spring-boot-starter-aop - This starter is used for aspect-oriented programming with Spring AOP and AspectJ.
❑spring-boot-starter-data-jdbc - This starter is used for Spring Data JDBC.
❑spring-boot-starter-data-jpa - This starter is used for Spring Data JPA with Hibernate.
❑spring-boot-starter-web - This starter is used for building a web application using Spring MVC and Spring REST. It
also provides Tomcat as the default embedded container.
❑spring-boot-starter-test - This starter provides support for testing Spring Boot applications using libraries such as
JUnit, Hamcrest, and Mockito.
4
ADITYA
Runner classes are used to deal with one-time executing logics and those logics will be executed where
SpringApplication.run(-) is about to complete all of its startup activities.
There are 2 Types of Runners
❑ CommandLineRunner
❑ ApplicationRunner
➢CommandLineRunner
It's a legacy runner which was introduced in SpringBoot 1.0 version.
It has only one abstract method “run(String… args): void”.
t is a Functional Interface having only one abstract method i.e "void run(String… args)".
Add one stereotype Annotation over Implementation class level (Ex:- @Component). So that container can detect
the class and create the object.
➢ApplicationRunner(I)
It is a new type of runner added in Spring boot 1.3 which makes it easy to access arguments.
This will separate Option Arguments (as Map<String, List<String>>) and Non-Option Arguments (<List<String>)
5
ADITYA
How To Pass Data to Runners:
We Programmers can pass data using Command Line Arguments, in two formats Option and Non-option
arguments.
Syntax:
--Key = Val for optional arguments.
value for non Optional arguments.
Example's for Optional arguments:
--db=oracle, --env=prod
Example's for NonOptional arguments:
Test clean execute etc...
Arguments data will be converted to String[] and send to CommandLineRunner Classes. We can access the data
based on index format.
Difference Between CommandLineRunner and ApplicationRunner
The working of both CommandLineRunner and ApplicationRunner processes is the same, but
CommandLineRunner holds the data in the String[] format whereas Application (AR) holds data as
ApllicationArguments as Option/Non-Option format. 6
ADITYA
7
ADITYA
8
ADITYA
❑A filter (if it is present) determines whether the LogRecord should be forwarded or not. As the name suggests, it
filters the log messages according to specific criteria.
❑A LogRecord is only passed from the logger to the log handler and from the log handler to external systems if it
passes the specified criteria.
// set a filter logger.setFilter(filter);
// get a filter Filter filter = logger.getFilter();
❑Handlers(Appenders)
The log handler or the appenders receive the LogRecord and exports it to various targets.
Java SE provides 5 built-in handlers:
logger.addHandler(handler);
// example
Handler handler = new ConsoleHandler();
logger.addHandler(handler);
9
ADITYA
Formatters
A handler can also use a Formatter to format the LogRecord object into a string before exporting it to external
systems.
Java SE has two built-in Formatters:
Advantages of Logging
Here are some of the advantages of logging in Java.
❑helps in monitoring the flow of the program
❑helps in capturing any errors that may occur
❑provides support for problem diagnosis and debugging
10
ADITYA
By using Log Files ,Dev/Support Teams identifies the mistakes and Fix Code
Log4J Components
a)Logger(which class) b)Appender(where to print) c)Layout(how to print)
❑Logger :This object must be created inside class for which Log4J is required
❑Appender: is used to specify where to store Log message
Types of Appenders
➢FileAppender: used to append log events to a file. It supports two more appender classes
➢ConsoleAppender: Appends log events to System.err or System.out using a layout specified by the user.
The default console is System.out.
➢JDBCAppender: Used for Database.
➢SMTPAppender: Used to send an email when a specific logging event occurs, typically on errors or fatal
errors.
➢SocketAppender: Used for remote storage.
➢SyslogAppender: Sends messages to a remote Syslog domain.
➢TelnetAppender: Specializes in writing to a read-only socket.
11
ADITYA
13
ADITYA
A default spring boot log file contains the following items:
▪Date and Time: This provides the occurrence date and time of the log item.
▪Log Level: This provides the information on what level of information the log is of. It will be one out of the 7 options we will
see now, i.e. TRACE, DEBUG, INFO, WARN, ERROR, FATAL or OFF.
▪Process ID: This provides the information of the process ID on which the spring boot application is running on.
▪Separator: — This is a separator which signifies the next part of the log.
▪Thread Name: This is enclosed within a square ( [ ] ) brackets and mostly contains the thread within which the logging thread or
element is present.
▪Logger Name: This is the penultimate element that contains the source class name.
▪Log Message: Finally, this element contains the log message, which explains the methods followed in the application and helps
us tracing back to the root cause if an error pops up in the application.
❑Thymeleaf is a java template engine, Commonly used to generate the HTML views for the web.
➢It is a general-purpose template engine which is capable of both web and standalone environment to
generate dynamic views.
➢It is a separate project, unrelated to spring we can create views without the use of spring.
❑Thymeleaf template
➢A thymeleaf template can be a combination of HTML tags with some thymeleaf expressions.
➢It includes dynamic content to an HTML page with the help of thymeleaf expressions.
➢It can access java code, objects, spring beans, and so on.
15
ADITYA
16
ADITYA
17
ADITYA
❑Aspect Oriented Programming (AOP) is a programming paradigm aiming to extract cross-cutting
functionalities, such as logging, into what’s known as “Aspects”.
❑This is achieved by adding behavior (“Advice”) to existing code without changing the code itself. We
specify which code we want to add the behavior to using special expressions (“Pointcuts”).
❑AOP breaks the program logic into separate parts called concerns. The functions that span multiple
points of a web application are named cross-cutting concerns and these cross-cutting concerns are
conceptually separate from the application's business logic.
❑There are various common useful examples of aspects in software development like logging, auditing,
declarative transactions, security, caching, etc. The key unit of modularity in OOP is the class, whereas
in AOP the unit of modularity is the aspect.
❑Spring AOP takes out the direct dependency of crosscutting tasks from classes that we can’t achieve
through normal object oriented programming model. For example, we can have a separate class for
logging but again the functional classes will have to call these methods to achieve logging across the
application. 18
Important Terminology of Spring Boot AOP ADITYA
Aspect: Aspect is a class that contains cross-cutting concerns i.e the additional service like transaction,
logging, validation, and etc. This class is annotated by @Aspect.
@Aspect
public class LogService{
//code begins here...
}
Advice: It is the method inside the aspect class that provides
the actual implementation.
@Aspect
public class LogService{
public void startsLog() {
System.out.println("LOG STARTS..");
}
}
Pointcut: It is an expression that will select the business method which needs advice. It is defined using
expression.
Joinpoint: It is a point in the application where the classes/business method links with pointcut.
Target: An object that is being advised by one or more aspects is Target Object.
19
ADITYA
Weaving: Weaving links aspects with other application types or objects to create an advised object. Spring AOP
performs weaving at runtime.
Proxy: It is the final output that contains advice and target objects. Spring boot uses JDK Dynamic proxy to create
proxy classes.
20
Bussiness Logic ADITYA
}
SPRING AOP
21
ADITYA
Beans are fundamental components in Spring framework that are managed by the Spring container. They represent
objects that are created, configured, and managed by the Spring framework to provide various functionalities in a
Spring application. One important aspect of beans in Spring is their scope, which determines how they are
instantiated and managed by the container.
Spring beans can have different scopes that indicate how their lifecycle and availability will be managed in the
context of the application. Some of the most common scopes for Spring beans are:
❑Singleton
❑Prototype
❑Request
❑Session
❑Application
❑WebSocket
22
ADITYA
Singleton
When a bean has a singleton scope, it means that only a single instance of the bean is created per Spring
application context. This instance is stored in memory and reused each time the bean is requested in the future,
rather than creating a new instance for each request.
@Component
@Scope("singleton")
public class SingletonBean {
}
When a bean has a request scope, it means that a new instance of the bean is created for each HTTP
request that arrives at the server. This instance of the bean will be available for the duration of the processing of
that specific request, and will be destroyed at the end of the request.
❑Session
When a bean has a session scope, it means that a single instance of the bean is created for each HTTP
session that is established in the application. This instance of the bean will be available for the duration of the
user’s session, and will be destroyed at the end of the session.
❑Application
The application scope in Spring can be used to define beans whose instances are intended to be shared
globally throughout the application, meaning that they can be accessed from anywhere in the application
at any time.
❑WebSocket
The WebSocket Scope type is a special type in which the bean that is created lasts for the duration of the
WebSocket session.
This Scope type is used to create WebSocket applications, for example for bidirectional message exchange
between client and server. This type of Scope will live as long as the WebSocket session is alive. We can also
25
say that it exhibits singleton behavior, but limited to a WebSocket session only.
ADITYA