0% found this document useful (0 votes)
24 views74 pages

Api&ms Uniti, Ii, Iii

This document provides an overview of Spring Framework 5, detailing its purpose, features, and modules, particularly focusing on Dependency Injection (DI) and Inversion of Control (IoC) for creating loosely coupled applications. It introduces the InfyTel Customer Application as a case study to illustrate the development of a three-tier application using Spring Boot, emphasizing the importance of service and persistence layers. The document also outlines the differences between BeanFactory and ApplicationContext containers, highlighting the advantages of using ApplicationContext for enterprise application development.

Uploaded by

chiru22f01a0560
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views74 pages

Api&ms Uniti, Ii, Iii

This document provides an overview of Spring Framework 5, detailing its purpose, features, and modules, particularly focusing on Dependency Injection (DI) and Inversion of Control (IoC) for creating loosely coupled applications. It introduces the InfyTel Customer Application as a case study to illustrate the development of a three-tier application using Spring Boot, emphasizing the importance of service and persistence layers. The document also outlines the differences between BeanFactory and ApplicationContext containers, highlighting the advantages of using ApplicationContext for enterprise application development.

Uploaded by

chiru22f01a0560
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

API&MICROSERVICES-IV-1-R20 UNIT-I

UNIT-1: Spring 5 Basics : Why Spring, What is Spring Framework, Spring Framework - Modules,
Configuring IoC container using Java-based configuration, Introduction To Dependency Injection,
Constructor Injection, Setter Injection, What is AutoScanning..

Spring is a popular open-source Java application development framework created by Rod Johnson.
Spring supports developing any kind of Java application such as standalone applications, web
applications, database-driven applications, and many more.

The basic objective of the framework was to reduce the complexity involved in the development of
enterprise applications. But today Spring is not limited to enterprise application development, many
projects are available under the Spring umbrella to develop different kinds of applications of today’s
need such as cloud-based applications, mobile applications, batch applications, etc. Spring framework
helps in developing a loosely coupled application that is simple, easily testable, reusable, and
maintainable.

Spring is a Java-based framework for constructing web and enterprise applications. However, configuring
a Spring application is a tedious job. Even though it provides flexibility in bean configuration with
multiple ways such as XML, annotation, and Java-based configurations, there is no escape from the
configuration. Configuring the Spring features may need more time for developers and may distract the
developers from solving business problems.

Thanks to Spring Team for releasing Spring Boot, one of the topmost innovations in all the existing Spring
Framework. Spring Boot provides a new prototype for developing Spring applications with nominal
effort. Using Spring Boot, you will be able to develop Spring applications with extra agility and capacity
to focus on solving business needs with nominal (or possibly no) configuring.

In this course, we will discuss the core concepts of Spring Framework using Spring Boot that makes it
easy to create a production-grade, stand-alone application that we can just run.

Scenario: InfyTel Customer Application:


In this course, we will look at a telecom application called InfyTel. InfyTel application is a Rest based
Application that provides functionality for adding, updating, and deleting a customer.

As the course proceeds, we will build this application incrementally to make it for learning the Spring
core concepts with Spring Boot.

InfyTel is built as a three-tier application which consists of

T.SESHASAI,DEPT OF CSE,SACET 1
API&MICROSERVICES-IV-1-R20 UNIT-I

 Presentation Layer

 Service/Business Layer

 Persistence Layer

The service layer of an enterprise application is the layer in which the business logic is implemented. It
interacts with the persistence layer and the presentation layer.In this course Spring Core with Boot, we
will see how to develop the Service/Business layer for this application. Once you have completed this
course you can then learn to build the Persistence layer using Spring JDBC with Spring Boot course and,
to build the Rest presentation layer using Spring REST course.

The InfyTel Application Architecture is as follows

In this course, we will develop the service layer of this application and we will hardcode the persistence
layer.

Below are the classes used in the InfyTel application.

 CustomerService.java -> Interface to define service methods

 CustomerServiceImpl.java -> A service class which implements the CustomerService interface

 Client.java-> A class for the main method.

T.SESHASAI,DEPT OF CSE,SACET 2
API&MICROSERVICES-IV-1-R20 UNIT-I

 CustomerRepository.java-> A class for the persistence layer where all CRUD operations are
performed.

Introduction to spring Framework:


in this module helped us learn the following:
1.what is the spring framework 2.why spring is needed 3. Different modules of the spring Framework.
Why Spring:
Consider our InfyTel application here, we have a CustomerServiceImpl class which implements the
CustomerService interface.

package com.infy.service;

public interface CustomerService {

public String fetchCustomer();

public String createCustomer(CustomerDtodto)

The business logic of InfyTel application is implemented in this class. This class is used to perform
operations like creating a customer, deleting a customer, etc... CustomerServiceImpl class interacts with
CustomerRepository to perform the database related operations.

Below is the implementation of CustomerServiceImpl class:

CustomerServiceImpl.java

public class CustomerServiceImpl implements CustomerService{

CustomerRepositorycustomerRepository= new CustomerRepositoryImpl();

public String createCustomer(CustomerDtodto) {

return customerRepository.createCustomer(dto);

public String fetchCustomer() {

return customerRepository.fetchCustomer();

T.SESHASAI,DEPT OF CSE,SACET 3
API&MICROSERVICES-IV-1-R20 UNIT-I

In this implementation, CustomeServiceImpl depends on CustomerRepository. It also instantiates


CustomerRepositoryImpl class which makes it tightly coupled with CustomerRepositoryImpl class. This is
a bad design because of the following reasons:

 If you want to unit test for createCustomer() method then you need a mock object of
CustomerRepository. But you cannot use a mock object because there is no way to substitute
the CustomerRepositoryImpl object that CustomerServiceImpl has. So testing
CustomerServiceImpl becomes difficult.

 Also, you cannot use a different implementation of CustomerRepository other than


CustomerRepositoryImpl because of tight coupling.

So we need a more flexible solution where dependencies can be provided externally rather than a
dependent creating its own dependencies. Now let us see such an implementation
of CustomerServiceImpl class.

Consider the following modified implementation of CustomerServiceImpl class:

public class CustomerServiceImpl implements CustomerService {

private CustomerRepositorycustomerRepository;

public CustomerServiceImpl(CustomerRepositorycustomerRepository) {

this.customerRepository = customerRepository;

public String createCustomer(CustomerDtodto) {

return customerRepository.createCustomer(dto);

}
In this implementation, CustomerServiceImpl doesn’t create an object of the CustomerRepository.
Instead, it is giving an object of CustomerRepository at creation time as a constructor argument. You can
pass the object of any class that implements CustomerRepository interface at the time of object creation
of CustomerServiceImpl class as a constructor argument. This makes CustomerServiceImpl class loosely
coupled with CustomerRepositoryImpl class. So you can now easily test CustomerServiceImpl class by
substituting its CustomerRepositoryImpl object with a mock CustomerRepository. Also, you can use any
implementations of CustomerRepository inside CustomerServiceImpl.

This solution is more flexible and easy to test. But at the same time, it is tedious to manually wire
together with the dependencies. Also if you alter the dependencies you may have to change vast
amounts of code. So what is the solution?

We can use a technique called Dependency Injection (DI). It is a technique in which the responsibility of
creating and wiring the dependencies of a dependent class is externalized to the external framework or

T.SESHASAI,DEPT OF CSE,SACET 4
API&MICROSERVICES-IV-1-R20 UNIT-I

library called dependency injection (DI) frameworks. So now the control over the construction and wiring
of an object graph is no longer resides with the dependent classes themselves. This reversal of
responsibilities is known as Inversion of Control(IoC). Dependency injection framework also called IoC
containers.

There are many third-party frameworks that are available for dependency injection such as Spring
Framework, Google Guice, Play Framework, etc. In this course, you will study about Spring Framework.
Besides dependency injection, there are many other advantages of using the Spring Framework which
you will study later in this course.

Note: Inversion of Control (IoC) represents the inversion of application responsibility of the object's
creation, initialization, dependency, and destruction from the application to the third party.

What is Spring Framework:


Spring Framework is an open source Java application development framework that supports developing
all types of Java applications such as enterprise applications, web applications, cloud based applications,
and many more.

Java applications developed using Spring are simple, easily testable, reusable, and maintainable.

Spring modules do not have tight coupling on each other, the developer can pick and choose the
modules as per the need for building an enterprise application.

The following are the main features of the Spring Framework.

Spring Feature Description

Spring JARs are relatively small.

A basic Spring framework would be lesser than 10MB.


Light Weight
It can be deployed in Tomcat and they do not require heavy-weight
application servers.

The application is developed using POJOs.


Non-Invasive
No need to extend/implement any pre-defined classes.

Spring features like Dependency Injection and Aspect Oriented Programming


Loosely Coupled
help in loosely coupled code.

IoC takes care of the application object's life cycle along with their
Inversion of Control(IoC)
dependencies.

Spring Container takes care of object creation, initialization, and managing


Spring Container
object dependencies.

Aspect Oriented Promotes separation of supporting functions(concerns) such as logging,

T.SESHASAI,DEPT OF CSE,SACET 5
API&MICROSERVICES-IV-1-R20 UNIT-I

Programming(AOP) transaction, and security from the core business logic of the application.

Spring Framework – Modules:


Spring Framework 5.x has the following key module groups:

 Core Container: These are core modules that provide key features of the Spring framework.

 Data Access/Integration: These modules support JDBC and ORM data access approaches in
Spring applications.

 Web: These modules provide support to implement web applications.

 Others: Spring also provides few other modules such as the Test for testing Spring applications.
 Core Container of Spring framework provides the Spring IoC container and Dependency
Injection features.

Core container has the following modules:

T.SESHASAI,DEPT OF CSE,SACET 6
API&MICROSERVICES-IV-1-R20 UNIT-I

 Core: This is the key module of Spring Framework which provides fundamental support on which
all other modules of the framework are dependent.

 Bean: This module provides a basic Spring container called BeanFactory.

 Context: This module provides one more Spring container called ApplicationContext which
inherits the basic features of the BeanFactory container and also provides additional features to
support enterprise application development.

 Spring Expression Language (SpEL): This module is used for querying/manipulating object values.

 AOP (Aspect Oriented Programming) and aspects: These modules help in isolating cross-cutting
functionality from business logic.

We will discuss BeanFactory and ApplicationContext containers in detail later in this course.

The Data Access/Integration module of Spring provides different data access approaches.

The following modules support Data Access/Integration:

 Java Database Connectivity (JDBC): It provides an abstract layer to support JDBC calls to
relational databases.

 Object Relational Mapping (ORM): It provides integration support for popular ORM(Object-
Relational Mapping) solutions such as Hibernate, JPA, etc.

 Transactions: It provides a simple transaction API which abstracts the complexity of underlying
repository specific transaction API's from the application.

Spring Framework Web module provides basic support for web application development. The Web
module has a web application context that is built on the application context of the core container. Web
module provides complete Model-View-Controller(MVC) implementation to develop a presentation tier
of the application and also supports a simpler way to implement RESTful web services.

T.SESHASAI,DEPT OF CSE,SACET 7
API&MICROSERVICES-IV-1-R20 UNIT-I

Spring Framework provides the following modules to support web application development:
 Web: This module has a container called web application context which inherits basic features
from ApplicationContext container and adds features to develop web based applications.

 Webmvc: It provides the implementation of the MVC(model-view-controller) pattern to


implement the serverside presentation layer and also supports features to implement RESTful
Web Services.

 WebFlux: Spring 5.0 introduced a reactive stack with a web framework called Spring WebFlux to
support Reactive programming in Spring's web layer and runs on containers such as Netty,
Undertow, and Servlet 3.1+.
 WebSocket: It is used for 2 way communication between client and server in WebSocket based
web applications.

Spring Framework has few additional modules, test module is one of the most commonly used ones
for testing Spring applications.

 Test: This module provides the required support to test Spring applications using TestNG or
JUnit.
 Overall this is the big picture of Spring Framework. In this course, we will be discussing the
highlighted modules in detail.

T.SESHASAI,DEPT OF CSE,SACET 8
API&MICROSERVICES-IV-1-R20 UNIT-I

Spring Version History:

The current version of Spring Framework is 5.x, the framework has been enhanced with new
features keeping core concepts the same as Spring 4.x.

At a high level, the new features of Spring Framework 5.x are:

 JDK baseline update


 Core framework revision
 Reactive Programming Model: Introduces a new non-blocking web framework called Spring
WebFlux
 Functional programming using Kotlin language support
 Testing improvements by supporting integration with JUnit5

Let us look at Spring core relevant changes in detail:

JDK baseline update

The entire Spring framework 5.x codebase runs on Java 8 and designed to work with Java 9.
Therefore, Java 8 is the minimum requirement to work on Spring Framework 5.x

Core framework revision

T.SESHASAI,DEPT OF CSE,SACET 9
API&MICROSERVICES-IV-1-R20 UNIT-I

The core Spring Framework 5.x has been revised, one of the main changes is Spring comes with its
own commons-logging through spring-jcl jar instead of standard Commons Logging.

There are few more changes in Spring 5.x with respect to library support and discontinued support,
you can refer to the Spring documentation for additional details.

Spring IoC (Inversion of Control):


As discussed earlier, usually it is the developer's responsibility to create the dependent application
object using the new operator in an application. Hence any change in the application dependency
requires code change and this results in more complexity as the application grows bigger.

Inversion of Control (IoC) helps in creating a more loosely coupled application. IoC represents the
inversion of the responsibility of the application object's creation, initialization, and destruction
from the application to the third party such as the framework. Now the third party takes care of
application object management and dependencies thereby making an application easy to maintain,
test, and reuse.

There are many approaches to implement IoC, Spring Framework provides IoC implementation
using Dependency Injection(DI).

Let us now learn more about Spring IoC through Dependency Injection.

Spring Container managed application objects are called beans in Spring.

We need not create objects in dependency injection instead describe how objects should be
created through configuration.

DI is a software design pattern that provides better software design to facilitate loose
coupling, reuse, and ease of testing.

Benefits of Dependency Injection(DI):

 Helps to create loosely coupled application architecture facilitating re-usability and easy
testing.
 Separation of responsibility by keeping code and configuration separately. Hence
dependencies can be easily modified using configuration without changing the code.
 Allows to replace actual objects with mock objects for testing, this improves testability
by writing simple JUnit tests that use mock objects.

The core container module of the Spring Framework provides IoC using Dependency Injection.

T.SESHASAI,DEPT OF CSE,SACET 10
API&MICROSERVICES-IV-1-R20 UNIT-I

The Spring container knows which objects to create and when to create through the
additional details that we provide in our application called Configuration Metadata.

1. Application logic is provided through POJO classes.

2. Configuration metadata consists of bean definitions that the container must manage.

3. IoC container produces objects required by the application using POJO classes and configuration
metadata. IoC container is of two types – BeanFactory and ApplicationContext.

Let us understand IoC containers and configuration metadata in detail on the go.

Spring IoC – Containers:

Spring provides two types of containers

T.SESHASAI,DEPT OF CSE,SACET 11
API&MICROSERVICES-IV-1-R20 UNIT-I

BeanFactory:

 It is the basic Spring container with features to instantiate, configure and manage the beans.

 org.springframework.beans.factory.BeanFactory is the main interface representing a


BeanFactory container.

ApplicationContext:

 ApplicationContext is another Spring container that is more commonly used in Spring


applications.

 org.springframework.context.ApplicationContext is the main Interface representing an


ApplicationContext container.

 It inherits the BeanFactory features and provides added features to support enterprise services
such as internationalization, validation, etc.

ApplicationContext is the preferred container for Spring application development. Let us look
at more details on the ApplicationContext container.

Let us now understand the differences between BeanFactory and ApplicationContext containers.

BeanFactory ApplicationContext

It does not support annotation based Support annotation based Dependency


Dependency Injection. Injection.

Support enterprise services such as


It does not support enterprise services.
validations, internationalization, etc.

By default, it supports Eager Loading.


By default, it supports Lazy Loading.
Beans are instantiated during load time.

// Loading ApplicationContext and


//Loading BeanFactory
instantiating bean
BeanFactory factory = new
ApplicationContext context = new
AnnotationConfigApplicationContext(SpringConfigur
AnnotationConfigApplicationContext(SpringConfig
ation.class);
uration.class);
// Instantiating bean during first access
// Instantiating bean during first access
using getBean()
using getBean()
CustomerServiceImpl service =
CustomerServiceImpl service =
(CustomerServiceImpl)
(CustomerServiceImpl)
factory.getBean("customerService");
context.getBean("customerService");

T.SESHASAI,DEPT OF CSE,SACET 12
API&MICROSERVICES-IV-1-R20 UNIT-I

org.springframework.context.annotation.AnnotationConfigApplicationContext is one of the


most commonly used implementation of ApplicationContext.

Example: ApplicationContext container instantiation.

ApplicationContext context = new


AnnotationConfigApplicationContext(SpringConfiguration.class);

Object obj = context.getBean("customerService");

1. ApplicationContext container is instantiated by loading the configuration from the


SpringConfiguration.class which is available in the utility package of the application.

2. Accessing the bean with id "customerService" from the container.

AbstractApplicationContext

You can see a warning message as Resource leak: 'context' is never closed while using the
ApplicationContext type. This is for the reason that you don’t have a close method with BeanFactory or
even ApplicationContext. AbstractApplicationContext is an abstract implementation of the
ApplicationContext interface and it implements Closeable and AutoCloseable interfaces. To close the
application context and destroy all beans in its abstractApplicationContext has a close method that
closes this application context.

There are different ways to access bean in Spring

1. The traditional way of accessing bean based on bean id with explicit typecast

CustomerServiceImpl service = (CustomerServiceImpl)

context.getBean("customerService");

2. Accessing bean based on class type to avoid typecast if there is a unique bean of type in
the container

CustomerServiceImpl service = context.getBean(CustomerServiceImpl.class);

3. Accessing bean through bean id and also type to avoid explicit typecast

CustomerServiceImpl service = context.getBean("customerService", CustomerServiceImpl.class);

The Spring configuration metadata consists of definitions of the beans that the container must manage.

T.SESHASAI,DEPT OF CSE,SACET 13
API&MICROSERVICES-IV-1-R20 UNIT-I

Spring allows providing the configuration metadata using :

 XML Configuration

 Annotation Based configuration

 Java Based configuration

We will cover the Java based configuration in this course.

Configuring IoC container using Java-based configuration:


The Java-based configuration metadata is provided in the Java class using the following annotations:
@Configuration: The Java configuration class is marked with this annotation. This annotation identifies
this as a configuration class, and it’s expected to contain details on beans that are to be created in the
Spring application context.

@Bean: This annotation is used to declare a bean. The methods of configuration class that creates an
instance of the desired bean are annotated with this annotation. These methods are called by the Spring
containers during bootstrap and the values returned by these methods are treated as Spring beans. By
default, only one bean instance is created for a bean definition by the Spring Container, and that
instance is used by the container for the whole application lifetime.

For example, the SpringConfiguration class can be configured in a Java class using the above annotations
as follows :

@Configuration

public class SpringConfiguration {

@Bean

public CustomerServiceImplcustomerService() {

return new CustomerServiceImpl();

By default, the bean name is the same as the name of the method in which the bean is configured. So in
the above code bean name is customerService. If you want to change the bean name then you can
either rename the method or provide a different name with the name attribute as follows:

@Configuration

public class SpringConfiguration { @Bean(name="service")

public CustomerServiceImplcustomerService() {

return new CustomerServiceImpl();

}}
T.SESHASAI,DEPT OF CSE,SACET 14
API&MICROSERVICES-IV-1-R20 UNIT-I

This module helped us learn the following:

 What is Inversion of Control in Spring?

 How to configure the IoC container using Java based configuration?

Introduction To Dependency Injection:


Let us now understand in detail how to implement Dependency Injection in Spring.

For the previously discussed InfyTel Customer application, we defined CustomerService bean as shown
below

@Bean

public CustomerServicecustomerService() {

return new CustomerService();

This is the same as the below Java code wherein an instance is created and initialized with default values
using the default constructor.

1. CustomerServicecustomerService = new CustomerService();

How do we initialize beans with some specific values in Spring?

This can be achieved through Dependency Injection in Spring.

Inversion of Control pattern is achieved through Dependency Injection (DI) in Spring. In Dependency
Injection, the developer need not create the objects but specify how they should be created through
configuration.

Spring container uses one of these two ways to initialize the properties:

 Constructor Injection: This is achieved when the container invokes a parameterized


constructor to initialize the properties of a class

 Setter Injection: This is achieved when the container invokes setter methods of a class to
initialize the properties after invoking a default constructor.

 Constructor Injection:
Constructor Injection - Primitive values

Let us consider the CustomerService class of InfyTel Customer application to understand constructor

injection.

T.SESHASAI,DEPT OF CSE,SACET 15
API&MICROSERVICES-IV-1-R20 UNIT-I

CustomerService class has a count property, let us now modify this class to initialize count property

during bean instantiation using the constructor injection approach.

1. package com.infy.service;

2. public class CustomerServiceImpl implements CustomerService {

3. private int count;

4. public CustomerServiceImpl(int count) {

5. this.count = count;

6. }

7. }

How do we define bean in the configuration to initialize values?

@Configuration

public class SpringConfiguration {

@Bean // CustomerService bean definition with bean dependencies through constructor injection

public CustomerServiceImplcustomerService() {

return new CustomerServiceImpl(20);

What is mandatory for constructor injection?

A parameterized constructor is required in the CustomerService class as we are injecting the values

through the constructor argument.

Can we use constructor injection to initialize multiple properties?

Yes, we can initialize more than one property.

Constructor Injection - Non primitive values:

T.SESHASAI,DEPT OF CSE,SACET 16
API&MICROSERVICES-IV-1-R20 UNIT-I

So far, we learned how to inject primitive values using constructor injection in Spring. Now we will

look into inject object dependencies using Constructor injection.

Consider our InfyTel Customer application. CustomerServiceImpl.java class which is dependent on

CustomerRepository(class used to in persistence layer to perform CRUD operations ) object type to

call fetchCustomer() method.

package com.infy.service;

public class CustomerServiceImpl implements CustomerService {

// CustomerServiceImpl needs to contact CustomerRepository, hence injecting the

customerRepository dependency

private CustomerRepositorycustomerRepository;

private int count;

public CustomerServiceImpl() {

public CustomerServiceImpl(CustomerRepositorycustomerRepository, int count) {

this.customerRepository = customerRepository;

this.count=count; }

public String fetchCustomer() {

return customerRepository.fetchCustomer(count);

public String createCustomer() {

return customerRepository.createCustomer(); }}

T.SESHASAI,DEPT OF CSE,SACET 17
API&MICROSERVICES-IV-1-R20 UNIT-I

Observe in the above code, CustomerRepository property of CustomerSevice class has not been

initialized with any value in the code. This is because Spring dependency is going to be taken care of

in the configuration.

How do we inject object dependencies through configuration using constructor injection?

package com.infy.util;

@Configuration

public class SpringConfiguration {

@Bean// customerRepository bean definition

public CustomerRepositorycustomerRepository() {

return new CustomerRepository();

@Bean // CustomerServic bean definition with bean dependencies through constructor injection

public CustomerServiceImplcustomerService() {

return new CustomerServiceImpl(customerRepository(),20);

Setter Injection:
Let us now understand Setter Injection in Spring.

In Setter Injection, Spring invokes setter methods of a class to initialize the properties after invoking a

default constructor.

How can we use setter injection to inject values for the primitive type of properties?

Consider the below example to understand setter injection for primitive types.

T.SESHASAI,DEPT OF CSE,SACET 18
API&MICROSERVICES-IV-1-R20 UNIT-I

Following the CustomerServiceImpl class has a count property, let us see how to initialize this property

during bean instantiation using the setter injection approach .


package com.infy.service;

public class CustomerServiceImpl implements CustomerService {

private int count;

public int getCount() {

return count;

public void setCount(int count) {

this.count = count;

public CustomerServiceImpl(){

How do we define bean in the configuration to initialize values?

1. package com.infy.util;

2. @Configuration

3. public class SpringConfiguration {

4. @Bean // CustomerService bean definition using Setter Injection

5. public CustomerServiceImplcustomerService() {

6. CustomerServiceImplcustomerService = new CustomerServiceImpl();

7. customerService.setCount(10);

T.SESHASAI,DEPT OF CSE,SACET 19
API&MICROSERVICES-IV-1-R20 UNIT-I

8. return customerService;

9. }}

What is mandatory to implement setter injection?

 Default constructor and setter methods of respective dependent properties are required in the

CustomerServiceImpl class. For setter injection, Spring internally uses the default constructor to

create a bean and then invokes a setter method of the respective property based on the name

attribute in order to initialize the values.


 So far, we learned how to inject primitive values using setter injection in Spring.
 How do we inject object dependencies using setter injection?
 Consider the CustomerServiceImpl class of InfyTel Customer application.
 package com.infy.service;
 public class CustomerServiceImpl implements CustomerService {
 private CustomerRepositorycustomerRepository;
 private int count;
 public CustomerRepositorygetCustomerRepository() {
 return customerRepository;
 }
 public void setCustomerRepository(CustomerRepositorycustomerRepository) {
 this.customerRepository = customerRepository;
 }
 public int getCount() {
 return count;
 }
 public void setCount(int count) {
 this.count = count;
 }
 }
 How do we inject object dependencies through configuration using setter injection?
 package com.infy.util;
 @Configuration

 public class SpringConfiguration {

 @Bean
 public CustomerRepositorycustomerRepository() {
 return new CustomerRepository();
 }

 @Bean // Setter Injection

T.SESHASAI,DEPT OF CSE,SACET 20
API&MICROSERVICES-IV-1-R20 UNIT-I

 public CustomerServiceImplcustomerService() {
 CustomerServiceImplcustomerService = new CustomerServiceImpl();
 customerService.setCount(10);
 customerService.setCustomerRepository(customerRepository());
 return customerService;
 }
 }

This module helped us in learning the following:

 What is Dependency Injection?


 Different types of dependency injection in Spring
 Setter Dependency Injection
 Constructor Dependency Injection

What is AutoScanning:
Why Auto Scanning is needed?

As discussed in the previous example as a developer you have to declare all the bean definition

in SpringConfiguration class so that Spring container can detect and register your beans as below :

Is any other way to eliminate this tedious beans declaration?

Yes, Spring provides a way to automatically detect the beans to be injected and avoid even the bean
definitions within the Spring configuration file through Auto Scanning. In Auto Scanning, Spring
Framework automatically scans, detects, and instantiates the beans from the specified base package, if
there is no declaration for the beans in the SpringConfiguration class.

So your SpringConfiguration class will be looking as below:


T.SESHASAI,DEPT OF CSE,SACET 21
API&MICROSERVICES-IV-1-R20 UNIT-I

@Configuration

@ComponentScan(basePackages="com.infy")

public class SpringConfiguration {

Component scanning isn’t turned on by default, however. You have to annotate the configuration class
with @ComponentScan annotation to enable component scanning as follows:

1. @Configuration

2. @ComponentScan
3. publicclassSpringConfiguration{
4. }
In the above code, Spring will scan the package that contains SpringConfig class and it subpackages for
beans. But if you want to scan a different package or multiple packages then you can specify this
with the basePackages attribute as follows:

@Configuration

@ComponentScan(basePackages = "com.infy.service,com.infy.repository")

public class SpringConfiguration {

Spring uses @ComponentScan annotation for the auto scan feature. It looks for classes with the
stereotype annotations and creates beans for such classes automatically.

So what are Stereotype annotations?

 Stereotype annotations denote the roles of types or methods at the conceptual level.

 Stereotype annotations are @Component, @Service, @Repository,


and @Controller annotations.

 These annotations are used for auto-detection of beans using @ComponentScan.

 The Spring stereotype @Component is the parent stereotype.

 The other stereotypes are the specialization of @Component annotation.

Annotation Usage

@Component It indicates the class(POJO class) as a Spring component.

@Service It indicates the Service class(POJO class) in the business layer.

T.SESHASAI,DEPT OF CSE,SACET 22
API&MICROSERVICES-IV-1-R20 UNIT-I

Annotation Usage

@Repository It indicates the Repository class(POJO class in Spring DATA) in the persistence layer.

@Controller It indicates the Controller class(POJO class in Spring MVC) in the presentation layer.

 @Component is a generic stereotype for any Spring-managed component.

 @Repository, @Service, and @Controller are specializations of @Component for more specific
use cases.

 @Component should be used when your class does not fall into either of three categories
i.e. Controllers, Services, and DAOs.

@Component: It is a general purpose annotation to mark a class as a Spring-managed bean.

@Component

public class CustomerLogging{

//rest of the code

@Service - It is used to define a service layer Spring bean. It is a specialization of the @Component
annotation for the service layer.

1. @Service

2. public class CustomerSeviceImpl implements CustomerService {

3. //rest of the code

4. }

@Repository - It is used to define a persistence layer Spring bean. It is a specialization of


the @Component annotation for the persistence layer.

1. @Repository

2. public class CustomerRepositoryImpl implements CustomerRepository {

3. //rest of the code

4. }

@Controller - It is used to define a web component. It is a specialization of the @Component annotation


for the presentation layer.

1. @Controller

2. public class CustomerController {


T.SESHASAI,DEPT OF CSE,SACET 23
API&MICROSERVICES-IV-1-R20 UNIT-I

3. //rest of the code

4. }

By default, the bean names are derived from class names with a lowercase initial character. Therefore,
your above defined beans have the names customerController, customerServiceImpl, and
customerRepositoryImpl. It is also possible to give a specific name with a value attribute in those
annotations as follows:

1. @Repository(value="customerRepository")

2. public class CustomerRepositoryImpl implements CustomerRepository {

3. //rest of the code

4. }

Note: As a best practice, use @Service for the service layer, @Controller for the Presentation layer, and
@Repository for the Persistence layer.

Highlights:

Objective: To understand the AutoScanning feature in Spring

Demo Steps:

SpringConfiguration .java

1. package com.infy.util;

2.

3. import org.springframework.context.annotation.ComponentScan;

4. import org.springframework.context.annotation.Configuration;

5.

6. @Configuration

7. @ComponentScan(basePackages="com.infy")

8. public class SpringConfiguration {

9. }

CustomerService.java

1. package com.infy.service;

2. public interface CustomerService {

T.SESHASAI,DEPT OF CSE,SACET 24
API&MICROSERVICES-IV-1-R20 UNIT-I

3. public String fetchCustomer(int count);

4. public String createCustomer();

5. }

CustomerServiceImpl.java

1. package com.infy.service;

2. import org.springframework.beans.factory.annotation.Value;

3. import org.springframework.stereotype.Service;

4. @Service("customerService")

5. public class CustomerServiceImpl implements CustomerService {

6. @Value("10")

7. private int count;

8. public String fetchCustomer(int count) {

9. return " The no of customers fetched are : " + count;

10. }

11. public String createCustomer() {

12. return "Customer is successfully created";

13. }

14. }

Client.java

1. package com.infy;

2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;

3. import org.springframework.context.support.AbstractApplicationContext;

4. import com.infy.service.CustomerServiceImpl;

5. import com.infy.util.SpringConfiguration;

6. public class Client {

7. public static void main(String[] args) {

8. CustomerServiceImpl service = null;

T.SESHASAI,DEPT OF CSE,SACET 25
API&MICROSERVICES-IV-1-R20 UNIT-I

9. AbstractApplicationContext context = new


AnnotationConfigApplicationContext(SpringConfiguration.class);

10. service = (CustomerServiceImpl) context.getBean("customerService");

11. System.out.println(service.createCustomer());

12. context.close();

13. }

14. }

Output:

1. Customer is successfully created

T.SESHASAI,DEPT OF CSE,SACET 26
API & MICROSERVICES UNIT:II

UNIT-II
Spring Boot: Creating a Spring Boot Application, Spring Boot Application Annotation, What is Auto wiring ,
Scope of a bean, Logger, Introduction to Spring AOP, Implementing AOP advices, Best Practices : Spring Boot
Application.

Why Spring Boot?

So far you have learned that Spring is a lightweight framework for developing enterprise Java applications. But
using Spring for application development is challenging for developer because of the following reason which
reduces productivity and increases the development time:

1. Configuration

You have seen that the Spring application requires a lot of configuration. This configuration also needs to be
overridden for different environments like production, development, testing, etc. For example, the database
used by the testing team may be different from the one used by the development team. So we have to spend a
lot of time writing configuration instead of writing application logic for solving business problems.

2. Project Dependency Management


When you develop a Spring application you have to search for all compatible dependencies for the Spring
version that you are using and then manually configure them. If the wrong version of dependencies is selected
then it will be an uphill task to solve this problem. Also for every new feature added to the application, the
appropriate dependency needs to be identified and added. All this reduces productivity.

So to handle all these kinds of challenges Spring Boot came into the market.

What is Spring Boot?

What is 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.

But how does it work? 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

 Automatic Configuration

 Spring Boot Actuator and Easy-to-use Embedded Servlet Container Support


T.SESHASAI,DEPT OF CSE 1
API & MICROSERVICES UNIT:II

1.Creating a Spring Boot Application:


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)

In this course, you will learn how to use Spring Initializr for creating Spring Boot applications.

It is an online tool provided by Spring for generating Spring Boot applications which is
accessible at http://start.spring.io/. You can use it for creating a Spring Boot project using the following steps:

Step 1: Create your Spring Boot application launch Spring Initializr. You will get the following screen:

Note: This screen keeps changing depending on updates from Pivotal and changes in the Spring Boot version.

Step 2: Select Project as Maven, Language as Java, and Spring Boot as 2.1.13 and enter the project details as
follows:

 Choose com.infy as Group

 Choose Demo_SpringBoot as Artifact

Click on More options and choose com.infy as Package Name

Step 3: Click on Generate Project. This would download a zip file to your local machine.

Step 4: Unzip the zip file and extract it to a folder.

T.SESHASAI,DEPT OF CSE 2
API & MICROSERVICES UNIT:II

Step 5: In Eclipse, Click File → Import → Existing Maven Project. Navigate or type in the path of the folder where
you extracted the zip file to the next screen. After finishing, our Spring Boot project should look like as follows:

You have created a Spring Boot Maven-based project. Now let us explore what is contained in the generated
project.

Understanding Spring Boot project structure

The generated project contains the following files:

1. pom.xml

This file contains information about the project and configuration details used by Maven to build the project.

T.SESHASAI,DEPT OF CSE 3
API & MICROSERVICES UNIT:II

2. 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.

3. 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.

4. DemoSpringBootApplicationTest.java

In this file test cases are written. This class is by default generated by Spring Boot to bootstrap Spring application.

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. For example, to use spring-boot-starter following dependency needs to be added in pom.xml:

Spring Boot comes with many starters. Some popular starters which we are going to use in this course are as follows:

 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.

T.SESHASAI,DEPT OF CSE 4
API & MICROSERVICES UNIT:II

 spring-boot-starter-test - This starter provides support for testing Spring Boot applications using libraries
such as JUnit, Hamcrest, and Mockito.

Spring Boot Starter Parent

The Spring Boot Starter Parent defines key versions of dependencies and default plugins for quickly building Spring
Boot applications. It is present in the pom.xml file of the application as a parent as follows:

It allows you to manage the following things for multiple child projects and modules:

 Configuration – The Java version and other properties.

 Dependencies – The version of dependencies.


 Default Plugins Configuration – This includes default configuration for Maven plugins such as maven-failsafe-
plugin, maven-jar-plugin, maven-surefire-plugin, maven-war-plugin.
 Executing the Spring Boot application
 To execute the Spring Boot application run the DemoSpringBootApplication as a standalone Java class which
contains the main method. On successful execution you will get the following output in the console:

Spring Boot Runners

So far you have learned how to create and start the Spring Boot application. Now suppose you want to perform
some action immediately after the application has started then for this Spring Boot provides the following two
interfaces:

 CommandLineRunner

 ApplicationRunner

T.SESHASAI,DEPT OF CSE 5
API & MICROSERVICES UNIT:II

CommandLineRunner is the Spring Boot interface with a run() method. Spring Boot automatically calls this method
of all beans implementing this interface after the application context has been loaded. To use this interface, you can
modify the DemoSpringBootApplication class as follows:

1. @SpringBootApplication

2. public class DemoSpringBootApplication implements CommandLineRunner {

3. public static void main(String[] args) {

4. SpringApplication.run(DemoSpringBootApplication.class, args);

5. }

6. @Override

7. public void run(String... args) throws Exception {

8. System.out.println("Welcome to CommandLineRunner");

9. }

10. }

Spring Boot application is configured using a file named application.properties. It is auto detected without any
Spring based configurations and is placed inside the "src/main/resources" directory as shown below:

In this file, various default properties are specified to support logging, AOP, JPA, etc. All the default properties need
not be specified in all cases. We can specify them only on-demand. At startup, the Spring application loads all the
properties and adds them to the Spring Environment class.

T.SESHASAI,DEPT OF CSE 6
API & MICROSERVICES UNIT:II

To use a custom property add it to the application.properties file.

application.properties

1. message= Welcome Spring

Then autowire the Environment class into a class where the property is required.

1. @Autowired Environment env;

You can read the property from Environment using the getProperty() method.

1. env.getProperty("message")

You can use other files to keep the properties. For example, InfyTelmessage.properties.

@PropertySource annotation
InfyTelmessage.properties

1. message=Welcome To InfyTel

But by default Spring Boot will load only the application.properties file. So how you will load
the InfyTelmessage.properties file?

In Spring @PropertySource annotation is used to read from properties file using Spring’s Environment interface. The
location of the properties file is mentioned in the Spring configuration file using @PropertySource annotation.

So InfyTelmessage.properties which are present in classpath can be loaded using @PropertySource as follows:

1.

2. import org.springframework.context.annotation.PropertySource;

3.

4. @SpringBootApplication

5. @PropertySource("classpath:InfyTelmessage.properties")

6. public class DemoSpringBootApplication {

7.

8. public static void main(String[] args) throws Exception {

9. //code

10. } }

T.SESHASAI,DEPT OF CSE 7
API & MICROSERVICES UNIT:II

To read the properties you need to autowire the Environment class into a class where the property is required

1. @Autowired

2. Environment env;

You can read the property from Environment using the getProperty() method.

1. env.getProperty("message")

2.SpringBootApplication Annotation:
@SpringBootApplication

This module helped us in learning the following:

 What is the Spring Boot?

 How to create a Spring Boot application?

We have already learned that the class which is used to bootstrap the Spring Boot application is annotated

with @SpringBootApplication annotation as follows:

Now let us understand this annotation in detail.


The @SpringBootApplication annotation indicates that it is a configuration class and also triggers auto-configuration
and component scanning. It is a combination of the following annotations with their default attributes:
@EnableAutoConfiguration – This annotation enables auto-configuration for the Spring boot application
which automatically configures our application based on the dependencies that you have added.

@ComponentScan – This enables the Spring bean dependency injection feature by using @Autowired annotation.
All application components which are annotated with @Component, @Service, @Repository, or @Controller are
automatically registered as Spring Beans. These beans can be injected by using @Autowired annotation.

@Configuration – This enables Java based configurations for Spring boot application.

The class that is annotated with @SpringBootApplication will be considered as the main class, is also a bootstrap
class. It kicks starts the application by invoking the SpringApplication.run() method. You need to pass the .class file
name of your main class to the run() method.

T.SESHASAI,DEPT OF CSE 8
API & MICROSERVICES UNIT:II

SpringBootApplication- scanBasePackages

By default, SpringApplication scans the configuration class package and all it’s sub-packages. So if
our SpringBootApplication class is in "com.eta" package, then it won’t scan com.infy.service
or com.infy.repository package. We can fix this situation using the SpringBootApplication scanBasePackages
property.

3.What is Autowiring ?
In Spring if one bean class is dependent on another bean class then the bean dependencies need to be explicitly
defined in your configuration class. But you can let the Spring IoC container to inject the dependencies into
dependent bean classes without been defined in your configuration class. This is called as autowiring.

To do autowiring, you can use @Autowired annotation. This annotation allows the Spring IoC container to resolve
and inject dependencies into your bean.@Autowired annotation performs byType Autowiring i.e. dependency is
injected based on bean type. It can be applied to attributes, constructors, setter methods of a bean class.

Autowiring is done only for dependencies to other beans. It doesn't work for properties such as primitive data types,
String, Enum, etc. For such properties, you can use the @Value annotation.

T.SESHASAI,DEPT OF CSE 9
API & MICROSERVICES UNIT:II

@Autowired on Setter methods

The @Autowired annotation can be used on setter methods. This is called a Setter Injection.

In the above code snippet, the Spring IoC container will call the setter method for injecting the dependency of
CustomerRepository.

@Autowired on Constructor

The @Autowired annotation can also be used on the constructor. This is called a Constructor Injection.

@Autowired on Properties

Let us now understand the usage of @Autowired on a property in Spring.

We will use @Autowired in the below code to wire the dependency of CustomerService class for
CustomerRepository bean dependency.

T.SESHASAI,DEPT OF CSE 10
API & MICROSERVICES UNIT:II

@Autowired is by default wire the dependency based on the type of bean.

In the above code, the Spring container will perform dependency injection using the Java Reflection API. It will
search for the class which implements CustomerRepository and injects its object. The dependencies which are
injected using @Autowired should be available to the Spring container when the dependent bean object is created.
If the container does not find a bean for autowiring, it will throw the NoSuchBeanDefinitionException exception.

If more than one beans of the same type are available in the container, then the framework throws an exception
indicating that more than one bean is available for autowiring. To handle this @Qualifier annotation is used as
follows:

In Spring @Value annotation is used to insert values into variables and method arguments. Using @Value we can
either read spring environment variables or system variables.

We can assign a default value to a class property with @Value annotation:

Note that it accepts only a String argument but the passed-in value gets converted to an appropriate type during
value-injection.

To read a Spring environment variable we can use @Value annotation:

T.SESHASAI,DEPT OF CSE 11
API & MICROSERVICES UNIT:II

4.Scope of a bean:
The lifetime of a bean depends on its scope. Bean's scope can be defined while declaring it in the configuration
metadata file.
A bean can be in singleton or prototype scope. A bean with the "singleton" scope is initialized during the container
starts up and the same bean instance is provided for every bean request from the application. However, in the case
of the "prototype" scope, a new bean instance is created for every bean request from the application.

Let us now understand about bean scope in detail.

There will be a single instance of "singleton" scope bean in the container and the same bean is given for every
request from the application.

The bean scope can be defined for a bean using @Scope annotation in Java class. By default, the scope of a bean is
the singleton

This module helped us in learning the following:

 What is Autowiring?

 Different types of Autowiring

 What are the scope of a bean and its different types?

For the "prototype" bean, there will be a new bean created for every request from the application.

In the below example, customerService bean is defined with prototype scope. There will be a
new customerService bean created for every bean request from the application.

T.SESHASAI,DEPT OF CSE 12
API & MICROSERVICES UNIT:II

5. Logger:
What is logging?

Logging is the process of writing log messages to a central location during the execution of the program. That means
Logging is the process of tracking the execution of a program, where

 Any event can be logged based on the interest to the

 When exception and error occurs we can record those relevant messages and those logs can be analyzed by
the programmer later

There are multiple reasons why we may need to capture the application activity.

 Recording unusual circumstances or errors that may be happening in the program

 Getting the info about what's going in the application

There are several logging APIs to make logging easier. Some of the popular ones are:

 JDK Logging API

 Apache Log4j

 Commons Logging API

T.SESHASAI,DEPT OF CSE 13
API & MICROSERVICES UNIT:II

The Logger is the object which performs the logging in applications.

Levels in the logger specify the severity of an event to be logged. The logging level is decided based on necessity. For
example, TRACE can be used during development and ERROR during deployment.

The following table shows the different levels of logging.

You know that logging is one of the important activities in any application. It helps in quick problem diagnosis,
debugging, and maintenance. Let us learn the logging configuration in Spring Boot.

While executing your Spring Boot application, have you seen things like the below getting printed on your console?

Do you have any guess what are these?

Yes, you are right. These are logging messaged logged on the INFO level. However, you haven't written any code for
logging in to your application. Then who does this?

By default, Spring Boot configures logging via Logback to log the activities of libraries that your application uses.

As a developer, you may want to log the information that helps in quick problem diagnosis, debugging, and
maintenance. So, let us see how to customize the default logging configuration of Spring Boot so that your
application can log the information that you are interested in and in your own format.

T.SESHASAI,DEPT OF CSE 14
API & MICROSERVICES UNIT:II

Log the error messages:

Have you realized that you have not done any of the below activities for logging which you typically do in any Spring
application?

 Adding dependent jars for logging

 Configuring logging through Java configuration or XML configuration

Still, you are able to log your messages. The reason is Spring Boot's default support for logging. The spring-boot-
starter dependency includes spring-boot-starter-logging dependency, which configures logging via Logback to log to
the console at the INFO level.

Spring Boot uses Commons Logging API with default configurations for Java Util Logging, Log4j 2, and Logback
implementation. Among these implementations, Logback configuration will be enabled by default.

You, as a developer, have just created an object for Logger and raise a request to log with your own message in
LoggingAspect.java as shown below.

T.SESHASAI,DEPT OF CSE 15
API & MICROSERVICES UNIT:II

Log the error messages using Logback:

The default log output contains the following information.

Date and Time

T.SESHASAI,DEPT OF CSE 16
API & MICROSERVICES UNIT:II

But, how to change this default configuration if you want to,

 log the message in a file rather than console

 log the message in your own pattern

 log the messages of a specific level

 use Log4j instead of Logback

Log:

Log into file

By default Spring Boot logs the message on the console. To log into a file, you have to include either logging.file or
logging. path property in your application.properties file.

Note: Please note that from Spring boot 2.3.X version onwards logging.file and logging.path has been deprecated we
should use "logging.file.name" and " logging.file.path" for the same.

Custom log pattern

Include logging.pattern.* property in application.properties file to write the log message in your own format.

Logging property Sample value Description

logging.pattern.console %d{yyyy-MM-dd HH:mm:ss,SSS} Specifies the log pattern to use on the console

logging.pattern.file %5p [%t] %c [%M] - %m%n Specifies the log pattern to use in a file

Custom log level

By default, the logger is configured at the INFO level. You can change this by configuring the logging.level.* property
in application.properties file as shown below.

T.SESHASAI,DEPT OF CSE 17
API & MICROSERVICES UNIT:II

Log4j instead of Logback

Since Spring Boot chooses Logback implementation by default, you need to exclude it and then include log4j 2
instead of in your pom.xml.

6.Introduction to Spring AOP:


AOP (Aspect Oriented Programming) is used for applying common behaviors like transactions, security, logging, etc.
to the application.

These common behaviors generally need to be called from multiple locations in an application. Hence, they are also
called as cross cutting concerns in AOP.

Spring AOP provides the solution to cross cutting concerns in a modularized and loosely coupled way.

Advantages

 AOP ensures that cross cutting concerns are kept separate from the core business logic.

 Based on the configurations provided, the Spring applies cross cutting concerns appropriately during the
program execution.

 This allows creating a more loosely coupled application wherein you can change the cross cutting concerns
code without affecting the business code.

 In Object Oriented Programming(OOP), the key unit of modularity is class. But in AOP the key unit of
modularity is an Aspect.

What is an Aspect?

Aspects are the cross-cutting concerns that cut across multiple classes.

Examples: Transaction Management, Logging, Security, etc.

For a better understanding of Aspect Oriented Programming(AOP) concepts let us consider a Banking scenario
comprising of BankAccount class with Withdraw and Deposit functionalities as shown below.

T.SESHASAI,DEPT OF CSE 18
API & MICROSERVICES UNIT:II

T.SESHASAI,DEPT OF CSE 19
API & MICROSERVICES UNIT:II

 Aspect is a class that implements cross-cutting concerns. To declare a class as an Aspect it should be
annotated with @Aspect annotation. It should be applied to the class which is annotated with @Component
annotation or with derivatives of it.

 Joinpoint is the specific point in the application such as method execution, exception handling, changing
object variable values, etc. In Spring AOP a join point is always the execution of a method.

 Advice is a method of the aspect class that provides the implementation for the cross-cutting concern. It gets
executed at the selected join point(s). The following table shows the different types of advice along with the
execution point they have

Type Of
Execution Point
Execution

Before Before advice is executed before the Joinpoint execution.

After advice will be executed after the execution of Joinpoint whether it returns with or without
After
exception. Similar to finally block in exception handling.

AfterReturning advice is executed after a Joinpoint executes and returns successfully without
AfterReturning
exceptions

AfterThrowing AfterThrowing advice is executed only when a Joinpoint exits by throwing an exception

Around advice is executed around the Joinpoints which means Around advice has some logic
Around which gets executed before Joinpoint invocation and some logic which gets executed after the
Joinpoint returns successfully

 Pointcut represents an expression that evaluates the method name before or after which the advice needs
to be executed.

 In Spring AOP, we need to modularize and define each of the cross cutting concerns in a single class
called Aspect.
 Each method of the Aspect which provides the implementation for the cross cutting concern is called Advice.
 The business methods of the program before or after which the advice can be called is known as a Joinpoint.
 The advice does not get inserted at every Joinpoint in the program.
 An Advice gets applied only to the Joinpoints that satisfy the Pointcut defined for the advice.
 Pointcut represents an expression that evaluates the business method name before or after which the advice
needs to be called.

T.SESHASAI,DEPT OF CSE 20
API & MICROSERVICES UNIT:II

A pointcut is an important part of AOP. So let us look at pointcut in detail.

Pointcut expressions have the following syntax:

1. execution(<modifiers> <return-type> <fully qualified class name>.<method-name>(parameters))

where,

 execution is called a pointcut designator. It tells Spring that joinpoint is the execution of the matching
method.

 <modifiers> determines the access specifier of the matching method. It is not mandatory and if not specified
defaults to the public.

 <return-type> determines the return type of the method in order for a join point to be matched. It is
mandatory. If the return type doesn't matter wildcard * is used.

 <fully qualified class name> specifies the fully qualified name of the class which has methods on the
execution of which advice gets executed. It is optional. You can also use * wildcard as a name or part of a
name.

 <method-name> specifies the name of the method on the execution of which advice gets executed. It is
mandatory. You can also use * wildcard as a name or part of a name.

 parameters are used for matching parameters. To skip parameter filtering, two dots( ..) are used in place
of parameters.

T.SESHASAI,DEPT OF CSE 21
API & MICROSERVICES UNIT:II

Pointcut Description

execution(public * *(..)) execution of any public methods

execution of any method with a name beginning with


execution(* service *(..))
"service"

execution of any method defined in


execution(*com.infy.service.CustomerServiceImpl.*(..))
CustomerServiceImpl of com.infy.service package

execution of any method defined in the


execution(* com.infy.service.*.*(..))
com.infy.service package

execution(public * execution of any public method of


com.infy.service.CustomerServiceImpl.*(..)) CustomerServiceImpl of com.infy.service package

execution of all public method of


execution(public String
CustomerServiceImpl of com.infy.service package that
com.infy.service.CustomerserviceImpl.*(..))
returns a String

To use Spring AOP and AspectJ in the Spring Boot project you have to add the spring-boot-starter-aop starter in the
pom.xml file as follows:

7. Implementing AOP advices:


Before Advice:

This advice is declared using @Before annotation. It is invoked before the actual method call. ie. This advice
is executed before the execution of fetchCustomer()methods of classes present in com.infy.service package. The
following is an example of this advice:

T.SESHASAI,DEPT OF CSE 22
API & MICROSERVICES UNIT:II

After Advice:

This advice is declared using @After annotation. It is executed after the execution of the actual
method(fetchCustomer), even if it throws an exception during execution. It is commonly used for resource cleanup
such as temporary files or closing database connections. The following is an example of this advice :

After Returning Advice

This advice is declared using @AfterReturning annotation. It gets executed after joinpoint finishes its execution. If
the target method throws an exception the advice is not executed. The following is an example of this advice that is
executed after the method execution of fetchCustomer()method of classes present in com.infy.service package.

You can also access the value returned by the joinpoint by defining the returning attribute of @AfterReturning
annotation as follows:

In the above code snippet, the value of the returning attribute is returnvalue which matches the name of the advice
method argument.

AfterThrowing Advice :

This advice is defined using @AfterThrowing annotation. It gets executed after an exception is thrown from the
target method. The following is an example of this advice that gets executed when exceptions are thrown from
the fetchCustomer() method of classes present in com.infy.service package. So it is marked
with @AfterThrowing annotation as follows:

T.SESHASAI,DEPT OF CSE 23
API & MICROSERVICES UNIT:II

You can also access the exception thrown from the target method inside the advice method as follows:

Around advice:

This advice gets executed around the joinpoint i.e. before and after the execution of the target method. It is declared
using @Around annotation. The following is an example of this advice:

In the above code snippet, aroundAdvice method accepts an instance of ProceedingJoinPoint as a parameter. It
extends the JoinPoint interface, and it can only be used in the Around advice. The proceed() method invokes the
joinpoint.

This module helped us in learning the following:

 What is AOP?

 Different types of Advices used in AOP

 How to implement AOP in Spring?

T.SESHASAI,DEPT OF CSE 24
API & MICROSERVICES UNIT:II

UNIT-II
Spring Boot: Creating a Spring Boot Application, Spring Boot Application Annotation, What is Auto wiring ,
Scope of a bean, Logger, Introduction to Spring AOP, Implementing AOP advices, Best Practices : Spring Boot
Application.

Why Spring Boot?

So far you have learned that Spring is a lightweight framework for developing enterprise Java applications. But
using Spring for application development is challenging for developer because of the following reason which
reduces productivity and increases the development time:

1. Configuration

You have seen that the Spring application requires a lot of configuration. This configuration also needs to be
overridden for different environments like production, development, testing, etc. For example, the database
used by the testing team may be different from the one used by the development team. So we have to spend a
lot of time writing configuration instead of writing application logic for solving business problems.

2. Project Dependency Management


When you develop a Spring application you have to search for all compatible dependencies for the Spring
version that you are using and then manually configure them. If the wrong version of dependencies is selected
then it will be an uphill task to solve this problem. Also for every new feature added to the application, the
appropriate dependency needs to be identified and added. All this reduces productivity.

So to handle all these kinds of challenges Spring Boot came into the market.

What is Spring Boot?

What is 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.

But how does it work? 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

 Automatic Configuration

 Spring Boot Actuator and Easy-to-use Embedded Servlet Container Support


T.SESHASAI,DEPT OF CSE 1
API & MICROSERVICES UNIT:II

1.Creating a Spring Boot Application:


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)

In this course, you will learn how to use Spring Initializr for creating Spring Boot applications.

It is an online tool provided by Spring for generating Spring Boot applications which is
accessible at http://start.spring.io/. You can use it for creating a Spring Boot project using the following steps:

Step 1: Create your Spring Boot application launch Spring Initializr. You will get the following screen:

Note: This screen keeps changing depending on updates from Pivotal and changes in the Spring Boot version.

Step 2: Select Project as Maven, Language as Java, and Spring Boot as 2.1.13 and enter the project details as
follows:

 Choose com.infy as Group

 Choose Demo_SpringBoot as Artifact

Click on More options and choose com.infy as Package Name

Step 3: Click on Generate Project. This would download a zip file to your local machine.

Step 4: Unzip the zip file and extract it to a folder.

T.SESHASAI,DEPT OF CSE 2
API & MICROSERVICES UNIT:II

Step 5: In Eclipse, Click File → Import → Existing Maven Project. Navigate or type in the path of the folder where
you extracted the zip file to the next screen. After finishing, our Spring Boot project should look like as follows:

You have created a Spring Boot Maven-based project. Now let us explore what is contained in the generated
project.

Understanding Spring Boot project structure

The generated project contains the following files:

1. pom.xml

This file contains information about the project and configuration details used by Maven to build the project.

T.SESHASAI,DEPT OF CSE 3
API & MICROSERVICES UNIT:II

2. 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.

3. 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.

4. DemoSpringBootApplicationTest.java

In this file test cases are written. This class is by default generated by Spring Boot to bootstrap Spring application.

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. For example, to use spring-boot-starter following dependency needs to be added in pom.xml:

Spring Boot comes with many starters. Some popular starters which we are going to use in this course are as follows:

 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.

T.SESHASAI,DEPT OF CSE 4
API & MICROSERVICES UNIT:II

 spring-boot-starter-test - This starter provides support for testing Spring Boot applications using libraries
such as JUnit, Hamcrest, and Mockito.

Spring Boot Starter Parent

The Spring Boot Starter Parent defines key versions of dependencies and default plugins for quickly building Spring
Boot applications. It is present in the pom.xml file of the application as a parent as follows:

It allows you to manage the following things for multiple child projects and modules:

 Configuration – The Java version and other properties.

 Dependencies – The version of dependencies.


 Default Plugins Configuration – This includes default configuration for Maven plugins such as maven-failsafe-
plugin, maven-jar-plugin, maven-surefire-plugin, maven-war-plugin.
 Executing the Spring Boot application
 To execute the Spring Boot application run the DemoSpringBootApplication as a standalone Java class which
contains the main method. On successful execution you will get the following output in the console:

Spring Boot Runners

So far you have learned how to create and start the Spring Boot application. Now suppose you want to perform
some action immediately after the application has started then for this Spring Boot provides the following two
interfaces:

 CommandLineRunner

 ApplicationRunner

T.SESHASAI,DEPT OF CSE 5
API & MICROSERVICES UNIT:II

CommandLineRunner is the Spring Boot interface with a run() method. Spring Boot automatically calls this method
of all beans implementing this interface after the application context has been loaded. To use this interface, you can
modify the DemoSpringBootApplication class as follows:

1. @SpringBootApplication

2. public class DemoSpringBootApplication implements CommandLineRunner {

3. public static void main(String[] args) {

4. SpringApplication.run(DemoSpringBootApplication.class, args);

5. }

6. @Override

7. public void run(String... args) throws Exception {

8. System.out.println("Welcome to CommandLineRunner");

9. }

10. }

Spring Boot application is configured using a file named application.properties. It is auto detected without any
Spring based configurations and is placed inside the "src/main/resources" directory as shown below:

In this file, various default properties are specified to support logging, AOP, JPA, etc. All the default properties need
not be specified in all cases. We can specify them only on-demand. At startup, the Spring application loads all the
properties and adds them to the Spring Environment class.

T.SESHASAI,DEPT OF CSE 6
API & MICROSERVICES UNIT:II

To use a custom property add it to the application.properties file.

application.properties

1. message= Welcome Spring

Then autowire the Environment class into a class where the property is required.

1. @Autowired Environment env;

You can read the property from Environment using the getProperty() method.

1. env.getProperty("message")

You can use other files to keep the properties. For example, InfyTelmessage.properties.

@PropertySource annotation
InfyTelmessage.properties

1. message=Welcome To InfyTel

But by default Spring Boot will load only the application.properties file. So how you will load
the InfyTelmessage.properties file?

In Spring @PropertySource annotation is used to read from properties file using Spring’s Environment interface. The
location of the properties file is mentioned in the Spring configuration file using @PropertySource annotation.

So InfyTelmessage.properties which are present in classpath can be loaded using @PropertySource as follows:

1.

2. import org.springframework.context.annotation.PropertySource;

3.

4. @SpringBootApplication

5. @PropertySource("classpath:InfyTelmessage.properties")

6. public class DemoSpringBootApplication {

7.

8. public static void main(String[] args) throws Exception {

9. //code

10. } }

T.SESHASAI,DEPT OF CSE 7
API & MICROSERVICES UNIT:II

To read the properties you need to autowire the Environment class into a class where the property is required

1. @Autowired

2. Environment env;

You can read the property from Environment using the getProperty() method.

1. env.getProperty("message")

2.SpringBootApplication Annotation:
@SpringBootApplication

This module helped us in learning the following:

 What is the Spring Boot?

 How to create a Spring Boot application?

We have already learned that the class which is used to bootstrap the Spring Boot application is annotated

with @SpringBootApplication annotation as follows:

Now let us understand this annotation in detail.


The @SpringBootApplication annotation indicates that it is a configuration class and also triggers auto-configuration
and component scanning. It is a combination of the following annotations with their default attributes:
@EnableAutoConfiguration – This annotation enables auto-configuration for the Spring boot application
which automatically configures our application based on the dependencies that you have added.

@ComponentScan – This enables the Spring bean dependency injection feature by using @Autowired annotation.
All application components which are annotated with @Component, @Service, @Repository, or @Controller are
automatically registered as Spring Beans. These beans can be injected by using @Autowired annotation.

@Configuration – This enables Java based configurations for Spring boot application.

The class that is annotated with @SpringBootApplication will be considered as the main class, is also a bootstrap
class. It kicks starts the application by invoking the SpringApplication.run() method. You need to pass the .class file
name of your main class to the run() method.

T.SESHASAI,DEPT OF CSE 8
API & MICROSERVICES UNIT:II

SpringBootApplication- scanBasePackages

By default, SpringApplication scans the configuration class package and all it’s sub-packages. So if
our SpringBootApplication class is in "com.eta" package, then it won’t scan com.infy.service
or com.infy.repository package. We can fix this situation using the SpringBootApplication scanBasePackages
property.

3.What is Autowiring ?
In Spring if one bean class is dependent on another bean class then the bean dependencies need to be explicitly
defined in your configuration class. But you can let the Spring IoC container to inject the dependencies into
dependent bean classes without been defined in your configuration class. This is called as autowiring.

To do autowiring, you can use @Autowired annotation. This annotation allows the Spring IoC container to resolve
and inject dependencies into your bean.@Autowired annotation performs byType Autowiring i.e. dependency is
injected based on bean type. It can be applied to attributes, constructors, setter methods of a bean class.

Autowiring is done only for dependencies to other beans. It doesn't work for properties such as primitive data types,
String, Enum, etc. For such properties, you can use the @Value annotation.

T.SESHASAI,DEPT OF CSE 9
API & MICROSERVICES UNIT:II

@Autowired on Setter methods

The @Autowired annotation can be used on setter methods. This is called a Setter Injection.

In the above code snippet, the Spring IoC container will call the setter method for injecting the dependency of
CustomerRepository.

@Autowired on Constructor

The @Autowired annotation can also be used on the constructor. This is called a Constructor Injection.

@Autowired on Properties

Let us now understand the usage of @Autowired on a property in Spring.

We will use @Autowired in the below code to wire the dependency of CustomerService class for
CustomerRepository bean dependency.

T.SESHASAI,DEPT OF CSE 10
API & MICROSERVICES UNIT:II

@Autowired is by default wire the dependency based on the type of bean.

In the above code, the Spring container will perform dependency injection using the Java Reflection API. It will
search for the class which implements CustomerRepository and injects its object. The dependencies which are
injected using @Autowired should be available to the Spring container when the dependent bean object is created.
If the container does not find a bean for autowiring, it will throw the NoSuchBeanDefinitionException exception.

If more than one beans of the same type are available in the container, then the framework throws an exception
indicating that more than one bean is available for autowiring. To handle this @Qualifier annotation is used as
follows:

In Spring @Value annotation is used to insert values into variables and method arguments. Using @Value we can
either read spring environment variables or system variables.

We can assign a default value to a class property with @Value annotation:

Note that it accepts only a String argument but the passed-in value gets converted to an appropriate type during
value-injection.

To read a Spring environment variable we can use @Value annotation:

T.SESHASAI,DEPT OF CSE 11
API & MICROSERVICES UNIT:II

4.Scope of a bean:
The lifetime of a bean depends on its scope. Bean's scope can be defined while declaring it in the configuration
metadata file.
A bean can be in singleton or prototype scope. A bean with the "singleton" scope is initialized during the container
starts up and the same bean instance is provided for every bean request from the application. However, in the case
of the "prototype" scope, a new bean instance is created for every bean request from the application.

Let us now understand about bean scope in detail.

There will be a single instance of "singleton" scope bean in the container and the same bean is given for every
request from the application.

The bean scope can be defined for a bean using @Scope annotation in Java class. By default, the scope of a bean is
the singleton

This module helped us in learning the following:

 What is Autowiring?

 Different types of Autowiring

 What are the scope of a bean and its different types?

For the "prototype" bean, there will be a new bean created for every request from the application.

In the below example, customerService bean is defined with prototype scope. There will be a
new customerService bean created for every bean request from the application.

T.SESHASAI,DEPT OF CSE 12
API & MICROSERVICES UNIT:II

5. Logger:
What is logging?

Logging is the process of writing log messages to a central location during the execution of the program. That means
Logging is the process of tracking the execution of a program, where

 Any event can be logged based on the interest to the

 When exception and error occurs we can record those relevant messages and those logs can be analyzed by
the programmer later

There are multiple reasons why we may need to capture the application activity.

 Recording unusual circumstances or errors that may be happening in the program

 Getting the info about what's going in the application

There are several logging APIs to make logging easier. Some of the popular ones are:

 JDK Logging API

 Apache Log4j

 Commons Logging API

T.SESHASAI,DEPT OF CSE 13
API & MICROSERVICES UNIT:II

The Logger is the object which performs the logging in applications.

Levels in the logger specify the severity of an event to be logged. The logging level is decided based on necessity. For
example, TRACE can be used during development and ERROR during deployment.

The following table shows the different levels of logging.

You know that logging is one of the important activities in any application. It helps in quick problem diagnosis,
debugging, and maintenance. Let us learn the logging configuration in Spring Boot.

While executing your Spring Boot application, have you seen things like the below getting printed on your console?

Do you have any guess what are these?

Yes, you are right. These are logging messaged logged on the INFO level. However, you haven't written any code for
logging in to your application. Then who does this?

By default, Spring Boot configures logging via Logback to log the activities of libraries that your application uses.

As a developer, you may want to log the information that helps in quick problem diagnosis, debugging, and
maintenance. So, let us see how to customize the default logging configuration of Spring Boot so that your
application can log the information that you are interested in and in your own format.

T.SESHASAI,DEPT OF CSE 14
API & MICROSERVICES UNIT:II

Log the error messages:

Have you realized that you have not done any of the below activities for logging which you typically do in any Spring
application?

 Adding dependent jars for logging

 Configuring logging through Java configuration or XML configuration

Still, you are able to log your messages. The reason is Spring Boot's default support for logging. The spring-boot-
starter dependency includes spring-boot-starter-logging dependency, which configures logging via Logback to log to
the console at the INFO level.

Spring Boot uses Commons Logging API with default configurations for Java Util Logging, Log4j 2, and Logback
implementation. Among these implementations, Logback configuration will be enabled by default.

You, as a developer, have just created an object for Logger and raise a request to log with your own message in
LoggingAspect.java as shown below.

T.SESHASAI,DEPT OF CSE 15
API & MICROSERVICES UNIT:II

Log the error messages using Logback:

The default log output contains the following information.

Date and Time

T.SESHASAI,DEPT OF CSE 16
API & MICROSERVICES UNIT:II

But, how to change this default configuration if you want to,

 log the message in a file rather than console

 log the message in your own pattern

 log the messages of a specific level

 use Log4j instead of Logback

Log:

Log into file

By default Spring Boot logs the message on the console. To log into a file, you have to include either logging.file or
logging. path property in your application.properties file.

Note: Please note that from Spring boot 2.3.X version onwards logging.file and logging.path has been deprecated we
should use "logging.file.name" and " logging.file.path" for the same.

Custom log pattern

Include logging.pattern.* property in application.properties file to write the log message in your own format.

Logging property Sample value Description

logging.pattern.console %d{yyyy-MM-dd HH:mm:ss,SSS} Specifies the log pattern to use on the console

logging.pattern.file %5p [%t] %c [%M] - %m%n Specifies the log pattern to use in a file

Custom log level

By default, the logger is configured at the INFO level. You can change this by configuring the logging.level.* property
in application.properties file as shown below.

T.SESHASAI,DEPT OF CSE 17
API & MICROSERVICES UNIT:II

Log4j instead of Logback

Since Spring Boot chooses Logback implementation by default, you need to exclude it and then include log4j 2
instead of in your pom.xml.

6.Introduction to Spring AOP:


AOP (Aspect Oriented Programming) is used for applying common behaviors like transactions, security, logging, etc.
to the application.

These common behaviors generally need to be called from multiple locations in an application. Hence, they are also
called as cross cutting concerns in AOP.

Spring AOP provides the solution to cross cutting concerns in a modularized and loosely coupled way.

Advantages

 AOP ensures that cross cutting concerns are kept separate from the core business logic.

 Based on the configurations provided, the Spring applies cross cutting concerns appropriately during the
program execution.

 This allows creating a more loosely coupled application wherein you can change the cross cutting concerns
code without affecting the business code.

 In Object Oriented Programming(OOP), the key unit of modularity is class. But in AOP the key unit of
modularity is an Aspect.

What is an Aspect?

Aspects are the cross-cutting concerns that cut across multiple classes.

Examples: Transaction Management, Logging, Security, etc.

For a better understanding of Aspect Oriented Programming(AOP) concepts let us consider a Banking scenario
comprising of BankAccount class with Withdraw and Deposit functionalities as shown below.

T.SESHASAI,DEPT OF CSE 18
API & MICROSERVICES UNIT:II

T.SESHASAI,DEPT OF CSE 19
API & MICROSERVICES UNIT:II

 Aspect is a class that implements cross-cutting concerns. To declare a class as an Aspect it should be
annotated with @Aspect annotation. It should be applied to the class which is annotated with @Component
annotation or with derivatives of it.

 Joinpoint is the specific point in the application such as method execution, exception handling, changing
object variable values, etc. In Spring AOP a join point is always the execution of a method.

 Advice is a method of the aspect class that provides the implementation for the cross-cutting concern. It gets
executed at the selected join point(s). The following table shows the different types of advice along with the
execution point they have

Type Of
Execution Point
Execution

Before Before advice is executed before the Joinpoint execution.

After advice will be executed after the execution of Joinpoint whether it returns with or without
After
exception. Similar to finally block in exception handling.

AfterReturning advice is executed after a Joinpoint executes and returns successfully without
AfterReturning
exceptions

AfterThrowing AfterThrowing advice is executed only when a Joinpoint exits by throwing an exception

Around advice is executed around the Joinpoints which means Around advice has some logic
Around which gets executed before Joinpoint invocation and some logic which gets executed after the
Joinpoint returns successfully

 Pointcut represents an expression that evaluates the method name before or after which the advice needs
to be executed.

 In Spring AOP, we need to modularize and define each of the cross cutting concerns in a single class
called Aspect.
 Each method of the Aspect which provides the implementation for the cross cutting concern is called Advice.
 The business methods of the program before or after which the advice can be called is known as a Joinpoint.
 The advice does not get inserted at every Joinpoint in the program.
 An Advice gets applied only to the Joinpoints that satisfy the Pointcut defined for the advice.
 Pointcut represents an expression that evaluates the business method name before or after which the advice
needs to be called.

T.SESHASAI,DEPT OF CSE 20
API & MICROSERVICES UNIT:II

A pointcut is an important part of AOP. So let us look at pointcut in detail.

Pointcut expressions have the following syntax:

1. execution(<modifiers> <return-type> <fully qualified class name>.<method-name>(parameters))

where,

 execution is called a pointcut designator. It tells Spring that joinpoint is the execution of the matching
method.

 <modifiers> determines the access specifier of the matching method. It is not mandatory and if not specified
defaults to the public.

 <return-type> determines the return type of the method in order for a join point to be matched. It is
mandatory. If the return type doesn't matter wildcard * is used.

 <fully qualified class name> specifies the fully qualified name of the class which has methods on the
execution of which advice gets executed. It is optional. You can also use * wildcard as a name or part of a
name.

 <method-name> specifies the name of the method on the execution of which advice gets executed. It is
mandatory. You can also use * wildcard as a name or part of a name.

 parameters are used for matching parameters. To skip parameter filtering, two dots( ..) are used in place
of parameters.

T.SESHASAI,DEPT OF CSE 21
API & MICROSERVICES UNIT:II

Pointcut Description

execution(public * *(..)) execution of any public methods

execution of any method with a name beginning with


execution(* service *(..))
"service"

execution of any method defined in


execution(*com.infy.service.CustomerServiceImpl.*(..))
CustomerServiceImpl of com.infy.service package

execution of any method defined in the


execution(* com.infy.service.*.*(..))
com.infy.service package

execution(public * execution of any public method of


com.infy.service.CustomerServiceImpl.*(..)) CustomerServiceImpl of com.infy.service package

execution of all public method of


execution(public String
CustomerServiceImpl of com.infy.service package that
com.infy.service.CustomerserviceImpl.*(..))
returns a String

To use Spring AOP and AspectJ in the Spring Boot project you have to add the spring-boot-starter-aop starter in the
pom.xml file as follows:

7. Implementing AOP advices:


Before Advice:

This advice is declared using @Before annotation. It is invoked before the actual method call. ie. This advice
is executed before the execution of fetchCustomer()methods of classes present in com.infy.service package. The
following is an example of this advice:

T.SESHASAI,DEPT OF CSE 22
API & MICROSERVICES UNIT:II

After Advice:

This advice is declared using @After annotation. It is executed after the execution of the actual
method(fetchCustomer), even if it throws an exception during execution. It is commonly used for resource cleanup
such as temporary files or closing database connections. The following is an example of this advice :

After Returning Advice

This advice is declared using @AfterReturning annotation. It gets executed after joinpoint finishes its execution. If
the target method throws an exception the advice is not executed. The following is an example of this advice that is
executed after the method execution of fetchCustomer()method of classes present in com.infy.service package.

You can also access the value returned by the joinpoint by defining the returning attribute of @AfterReturning
annotation as follows:

In the above code snippet, the value of the returning attribute is returnvalue which matches the name of the advice
method argument.

AfterThrowing Advice :

This advice is defined using @AfterThrowing annotation. It gets executed after an exception is thrown from the
target method. The following is an example of this advice that gets executed when exceptions are thrown from
the fetchCustomer() method of classes present in com.infy.service package. So it is marked
with @AfterThrowing annotation as follows:

T.SESHASAI,DEPT OF CSE 23
API & MICROSERVICES UNIT:II

You can also access the exception thrown from the target method inside the advice method as follows:

Around advice:

This advice gets executed around the joinpoint i.e. before and after the execution of the target method. It is declared
using @Around annotation. The following is an example of this advice:

In the above code snippet, aroundAdvice method accepts an instance of ProceedingJoinPoint as a parameter. It
extends the JoinPoint interface, and it can only be used in the Around advice. The proceed() method invokes the
joinpoint.

This module helped us in learning the following:

 What is AOP?

 Different types of Advices used in AOP

 How to implement AOP in Spring?

T.SESHASAI,DEPT OF CSE 24

You might also like