Api&ms Uniti, Ii, Iii
Api&ms Uniti, Ii, Iii
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.
As the course proceeds, we will build this application incrementally to make it for learning the Spring
core concepts with Spring Boot.
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.
In this course, we will develop the service layer of this application and we will hardcode the persistence
layer.
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.
package com.infy.service;
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.
CustomerServiceImpl.java
return customerRepository.createCustomer(dto);
return customerRepository.fetchCustomer();
T.SESHASAI,DEPT OF CSE,SACET 3
API&MICROSERVICES-IV-1-R20 UNIT-I
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.
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.
private CustomerRepositorycustomerRepository;
public CustomerServiceImpl(CustomerRepositorycustomerRepository) {
this.customerRepository = customerRepository;
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.
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.
IoC takes care of the application object's life cycle along with their
Inversion of Control(IoC)
dependencies.
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.
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.
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.
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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.
ApplicationContext:
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
T.SESHASAI,DEPT OF CSE,SACET 12
API&MICROSERVICES-IV-1-R20 UNIT-I
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.
1. The traditional way of accessing bean based on bean id with explicit typecast
context.getBean("customerService");
2. Accessing bean based on class type to avoid typecast if there is a unique bean of type in
the container
3. Accessing bean through bean id and also type to avoid explicit typecast
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
XML Configuration
@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
@Bean
public CustomerServiceImplcustomerService() {
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 CustomerServiceImplcustomerService() {
}}
T.SESHASAI,DEPT OF CSE,SACET 14
API&MICROSERVICES-IV-1-R20 UNIT-I
For the previously discussed InfyTel Customer application, we defined CustomerService bean as shown
below
@Bean
public CustomerServicecustomerService() {
This is the same as the below Java code wherein an instance is created and initialized with default values
using the default constructor.
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:
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
1. package com.infy.service;
5. this.count = count;
6. }
7. }
@Configuration
@Bean // CustomerService bean definition with bean dependencies through constructor injection
public CustomerServiceImplcustomerService() {
A parameterized constructor is required in the CustomerService class as we are injecting the 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
package com.infy.service;
customerRepository dependency
private CustomerRepositorycustomerRepository;
public CustomerServiceImpl() {
this.customerRepository = customerRepository;
this.count=count; }
return customerRepository.fetchCustomer(count);
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.
package com.infy.util;
@Configuration
public CustomerRepositorycustomerRepository() {
@Bean // CustomerServic bean definition with bean dependencies through constructor injection
public CustomerServiceImplcustomerService() {
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
return count;
this.count = count;
public CustomerServiceImpl(){
1. package com.infy.util;
2. @Configuration
5. public CustomerServiceImplcustomerService() {
7. customerService.setCount(10);
T.SESHASAI,DEPT OF CSE,SACET 19
API&MICROSERVICES-IV-1-R20 UNIT-I
8. return customerService;
9. }}
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
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;
}
}
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 :
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.
@Configuration
@ComponentScan(basePackages="com.infy")
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")
Spring uses @ComponentScan annotation for the auto scan feature. It looks for classes with the
stereotype annotations and creates beans for such classes automatically.
Stereotype annotations denote the roles of types or methods at the conceptual level.
Annotation Usage
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.
@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
@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
4. }
1. @Repository
4. }
1. @Controller
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")
4. }
Note: As a best practice, use @Service for the service layer, @Controller for the Presentation layer, and
@Repository for the Persistence layer.
Highlights:
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")
9. }
CustomerService.java
1. package com.infy.service;
T.SESHASAI,DEPT OF CSE,SACET 24
API&MICROSERVICES-IV-1-R20 UNIT-I
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")
6. @Value("10")
10. }
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;
T.SESHASAI,DEPT OF CSE,SACET 25
API&MICROSERVICES-IV-1-R20 UNIT-I
11. System.out.println(service.createCustomer());
12. context.close();
13. }
14. }
Output:
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.
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.
So to handle all these kinds of challenges Spring Boot came into the market.
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.
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.
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.
Starter Dependencies
Automatic Configuration
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:
Step 3: Click on Generate Project. This would download a zip file to your local machine.
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.
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 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-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.
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:
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
4. SpringApplication.run(DemoSpringBootApplication.class, args);
5. }
6. @Override
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
application.properties
Then autowire the Environment class into a class where the property is required.
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")
7.
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
We have already learned that the class which is used to bootstrap the Spring Boot application is annotated
@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
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
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
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.
Note that it accepts only a String argument but the passed-in value gets converted to an appropriate type during
value-injection.
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.
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
What is Autowiring?
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
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.
There are several logging APIs to make logging easier. Some of the popular ones are:
Apache Log4j
T.SESHASAI,DEPT OF CSE 13
API & MICROSERVICES UNIT:II
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.
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?
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
Have you realized that you have not done any of the below activities for logging which you typically do in any Spring
application?
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
T.SESHASAI,DEPT OF CSE 16
API & MICROSERVICES UNIT:II
Log:
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.
Include logging.pattern.* property in application.properties file to write the log message in your own format.
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
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
Since Spring Boot chooses Logback implementation by default, you need to exclude it and then include log4j 2
instead of in your pom.xml.
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.
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
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
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
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:
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 :
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.
What is AOP?
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.
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.
So to handle all these kinds of challenges Spring Boot came into the market.
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.
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.
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.
Starter Dependencies
Automatic Configuration
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:
Step 3: Click on Generate Project. This would download a zip file to your local machine.
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.
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 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-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.
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:
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
4. SpringApplication.run(DemoSpringBootApplication.class, args);
5. }
6. @Override
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
application.properties
Then autowire the Environment class into a class where the property is required.
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")
7.
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
We have already learned that the class which is used to bootstrap the Spring Boot application is annotated
@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
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
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
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.
Note that it accepts only a String argument but the passed-in value gets converted to an appropriate type during
value-injection.
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.
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
What is Autowiring?
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
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.
There are several logging APIs to make logging easier. Some of the popular ones are:
Apache Log4j
T.SESHASAI,DEPT OF CSE 13
API & MICROSERVICES UNIT:II
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.
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?
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
Have you realized that you have not done any of the below activities for logging which you typically do in any Spring
application?
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
T.SESHASAI,DEPT OF CSE 16
API & MICROSERVICES UNIT:II
Log:
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.
Include logging.pattern.* property in application.properties file to write the log message in your own format.
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
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
Since Spring Boot chooses Logback implementation by default, you need to exclude it and then include log4j 2
instead of in your pom.xml.
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.
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
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
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
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:
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 :
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.
What is AOP?
T.SESHASAI,DEPT OF CSE 24