0% found this document useful (0 votes)
3 views

YDP_API&MS_UNIT_II[1]

The document provides an overview of Spring Boot, a framework designed to simplify the development of Spring-based applications by reducing boilerplate configuration. It covers key features, project structure, starter dependencies, logging mechanisms, and the concept of Aspect-Oriented Programming (AOP) within Spring. Additionally, it explains the different scopes of Spring beans, such as singleton and prototype, and their implications on application behavior.

Uploaded by

balajikukkapalli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

YDP_API&MS_UNIT_II[1]

The document provides an overview of Spring Boot, a framework designed to simplify the development of Spring-based applications by reducing boilerplate configuration. It covers key features, project structure, starter dependencies, logging mechanisms, and the concept of Aspect-Oriented Programming (AOP) within Spring. Additionally, it explains the different scopes of Spring beans, such as singleton and prototype, and their implications on application behavior.

Uploaded by

balajikukkapalli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

API AND

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

❑Java allows us to create and capture log messages


and files through the process of logging.
❑In Java, logging requires frameworks and APIs.
Java has a built-in logging framework in
the java.util.logging package.
❑We can also use third-party frameworks like
Log4j, Logback, and many more for logging
purposes.
❑Each Logger has a level that determines the
importance of the log message. There are 7 basic
log levels
❑Each log level has an integer value that
determines their severity except for two special log
levels OFF and ALL.

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

The layout layer provides Layout objects which are used


to format logging information in different styles. It is
used to provide support to appender objects before
publishing logging information.
There are different types of layout classes in log4j:
❑SimpleLayout: It is used to format the output in a
very simple manner; it prints the Level, then a dash "-"
and then the log message.
❑PatternLayout: Used to format the output based on
conversion pattern specified or if none is specified, the
default conversion pattern is considered.
❑HTMLLayout: It formats the output as an HTML
table.
❑XMLLayout: It formats the output as an XML File.
12
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.

The 7 option falls in the following order of severity (low to high).


❑TRACE
❑DEBUG
❑INFO
❑WARN
❑ERROR
❑FATAL
❑OFF
14
ADITYA

❑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

Thymeleaf Standard Expression syntax


These are the standard thymeleaf expression syntax are used to perform different types of a task such as the
declaration of variables. They are also used to includes the external static files such as CSS and JavaScript etc. By
default, it supports five types.
❖Variable expressions:- ${…}.
❖Selection expressions:- *{…}.
❖Message (i18n) expressions :- #{…} .
❖Link (URL) expressions :- @{…} .
❖Fragment expressions:- ~{…}.

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

Class Demo Cross cutting logc


{ Class Add Service{
public void pdfreport(){
logging logging
//////logic
logging }
}
public void excelreport(){
logging
//////logic
logging
}

}
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 {
}

Key features of the singleton scope in Spring:


➢Single instance: Only one instance of the bean is created in the entire Spring application lifecycle.
Each time the bean is requested, the same previously created instance is returned, if it already exists.
➢Stored in memory: The bean instance is stored in memory, which means that it persists for the
lifetime of the application and is available for use at any time.
➢Shared: The same singleton bean is shared between different components or classes that inject it into
their Spring application context. This can have implications for concurrency and bean state, so care
must be taken when handling shared data in singleton beans.
➢Efficiency: Using singleton beans can improve the efficiency and performance of the application by
avoiding the overhead of creating multiple instances of the same bean for each request.
➢It is important to note that the singleton scope in Spring is the DEFAULT scope for beans, so if no
scope is specified, it is considered as singleton.
23
Prototype ADITYA
When a bean has a prototype scope, it means that a new instance of the bean is created each time it is requested. Unlike the
singleton scope, where a single instance of the bean is created and reused, in the prototype scope a new instance of the bean is
created on each request.
@Component
@Scope("prototype")
public class PrototypeBean {
}
Key features of the prototype scope in Spring:
➢New instance on each request: Each time a bean with “prototype” scope is requested, a new instance of the bean is created.
This means that each time the bean is injected or fetched, a new instance will be fetched.
➢No state sharing: Bean instances with prototype scope do not share their state with other bean instances. Each instance has its
own independent state and any modification to one bean instance will not affect other instances.
➢Unmanaged lifecycle: Unlike other scopes such as singleton or session, bean instances with “prototype” scope are not managed
completely by the Spring container. This means that Spring does not take care of destroying prototype bean instances when they
are no longer in use. It is the responsibility of the developer to manage the lifetime of prototype bean instances and release
resources appropriately.
➢Greater configuration flexibility: The prototype scope is more flexible in terms of configuration, as it allows multiple instances
of the same bean to be created with different configurations or parameters at runtime.
➢Higher resource consumption: Because a new instance of the bean is created for each request, the use of prototype scoped
beans may result in higher resource consumption compared to other scopes such as singleton or request, as more instances are
created and destroyed.
➢Suitable for objects with changing state: The prototype scope is suitable for beans whose state changes frequently and there is
no need to share state between different instances.
➢It is important to note that prototype scoping in Spring can be useful in situations where you need a new instance of the bean
on every request, and you want to have more flexibility in state and concurrency management. However, you should also24be
aware of the increased computational cost associated with creating new instances on each request.
❑Request ADITYA

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

You might also like