Spring Framework Note by Biswajit Saha
Spring Framework Note by Biswajit Saha
This spring tutorial provides in-depth concepts of Spring Framework with simplified examples. It
was developed by Rod Johnson in 2003. Spring framework makes the easy development of JavaEE
application.
Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides
support to various frameworks such as Struts,Hibernate,EJB .
The framework, in broader sense, can be defined as a structure where we find solution of the
various technical problems.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc. We will
learn these modules in next page. Let's understand the IOC and Dependency Injection first.
1. class Employee{
2. Address address;
3. Employee(){
4. address=new Address();
5. }
6. }
In such case, there is dependency between the Employee and Address (tight coupling). In the Inversion of
Control scenario, we do this something like this:
1. class Employee{
2. Address address;
3. Employee(Address address){
4. this.address=address;
5. }
6. }
Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is
moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to the IOC
container either by XML file or annotation.
1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write
too much code. It hides the basic steps of these technologies.
Let's take the example of JdbcTemplate, you don't need to write the code for exception handling, creating
connection, creating statement, committing transaction, closing connection etc. You need to write the code of
executing query only. Thus, it save a lot of JDBC code.
2) Loose Coupling
3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application require server to
run the application but Spring framework doesn't require server.
4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the
programmer to inherit any class or implement any interface. That is why it is said non-invasive.
5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy
development of JavaEE application.
Spring Modules
The Spring framework comprises of many modules such as core, beans, context, expression language, AOP,
Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc. These modules are
grouped into Test, Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC /
Remoting) as displayed in the following diagram.
Test
The Spring Core container contains core, beans, context and expression language (EL) modules.
Core and Beans
Context
Expression Language
It is an extension to the EL defined in JSP. It provides support to setting and getting property values, method
invocation, accessing collections and indexers, named variables, logical and arithmetic operators, retrieval of
objects by name etc.
These modules support aspect oriented programming implementation where you can use Advices, Pointcuts
etc. to decouple the code.
The instrumentation module provides support to class instrumentation and classloader implementations.
This group comprises of JDBC, ORM, OXM, JMS and Transaction modules. These modules basically provide
support to interact with the database.
Web
This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet. These modules provide support to
create web application.
IoC Container
The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets
informations from the XML file and works accordingly. The main tasks performed by IoC container are:
Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the BeanFactory, we need
to create the instance of XmlBeanFactory class as given below:
The constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to
create the object of BeanFactory.
Using ApplicationContext
1. ApplicationContext context =
2. new ClassPathXmlApplicationContext("applicationContext.xml");
The constructor of ClassPathXmlApplicationContext class receives string, so we can pass the name of the xml
file to create the instance of ApplicationContext.
Dependency Injection in Spring
Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so
that it can be easy to manage and test the application. Dependency Injection makes our programming code
loosely coupled. To understand the DI better, Let's understand the Dependency Lookup (DL) first:
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to
get the resource for example:
In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:
1. A obj = A.getA();
This way, we get the resource (instance of A class) by calling the static factory method getA().
lternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:
There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.
o tight coupling The dependency lookup approach makes the code tightly coupled. If resource is
changed, we need to perform a lot of modification in the code.
o Not easy for testing This approach creates a lot of problems while testing the application especially in
black box testing.
Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we
provide the information from the external source such as XML file. It makes our code loosely coupled and easier
for testing. In such case we write the code as:
1. class Employee{
2. Address address;
3.
4. Employee(Address address){
5. this.address=address;
6. }
7. public void setAddress(Address address){
8. this.address=address;
9. }
10.
11. }
In such case, instance of Address class is provided by external souce such as XML file either by constructor or
setter method.
o By Constructor
o By Setter method
Let's see the simple example to inject primitive and string-based values. We have created three files here:
o Employee.java
o applicationContext.xml
o Test.java
Employee.java
It is a simple class containing two fields id and name. There are four constructors and one method in this class.
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. public Employee() {System.out.println("def cons");}
8.
9. public Employee(int id) {this.id = id;}
10.
11. public Employee(String name) { this.name = name;}
12.
13. public Employee(int id, String name) {
14. this.id = id;
15. this.name = name;
16. }
17.
18. void show(){
19. System.out.println(id+" "+name);
20. }
21.
22. }
applicationContext.xml
We are providing the information into the bean by this file. The constructor-arg element invokes the
constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of
constructor-arg element will assign the specified value. The type attribute specifies that int parameter
constructor will be invoked.
This class gets the bean from the applicationContext.xml file and calls the show method.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)factory.getBean("e");
14. s.show();
15.
16. }
17. }
Output:10 null
If you don't specify the type attribute in the constructor-arg element, by default string type constructor will be
invoked.
1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="10"></constructor-arg>
4. </bean>
5. ....
If you change the bean element as given above, string parameter constructor will be invoked and the output
will be 0 10.
Output:0 10
1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="Sonoo"></constructor-arg>
4. </bean>
5. ....
Output: 0 Sonoo
Let's see the simple example to inject primitive and string-based values by setter method. We have created
three files here:
o Employee.java
o applicationContext.xml
o Test.java
Employee.java
It is a simple class containing three fields id, name and city with its setters and getters and a method to display
these informations.
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private String city;
7.
8. public int getId() {
9. return id;
10. }
11. public void setId(int id) {
12. this.id = id;
13. }
14. public String getName() {
15. return name;
16. }
17. public void setName(String name) {
18. this.name = name;
19. }
20.
21. public String getCity() {
22. return city;
23. }
24. public void setCity(String city) {
25. this.city = city;
26. }
27. void display(){
28. System.out.println(id+" "+name+" "+city);
29. }
30.
31. }
applicationContext.xml
We are providing the information into the bean by this file. The property element invokes the setter method.
The value subelement of property will assign the specified value.
This class gets the bean from the applicationContext.xml file and calls the display method.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee e=(Employee)factory.getBean("obj");
14. s.display();
15.
16. }
17. }
1. Partial dependency: can be injected using setter injection but it is not possible by constructor.
Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if
you want to pass information for only one property, it is possible by setter method only.
2. Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter
injection, IOC container will use the setter injection.
3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance
always like constructor. So setter injection is flexible than constructor injection.
Autowiring in Spring
Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses
setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with reference only.
Advantage of Autowiring
It requires the less code because we don't need to write the code to inject the dependency explicitly.
Disadvantage of Autowiring
No control of programmer.
Autowiring Modes
There are many autowiring modes:
2) byName The byName mode injects the object dependency according to name of the bean. In such case,
property name and bean name must be same. It internally calls setter method.
3) byType The byType mode injects the object dependency according to type. So property name and bean
name can be different. It internally calls setter method.
4) constructor The constructor mode injects the dependency by calling the constructor of the class. It calls the
constructor having large number of parameters.
1. factory-method: represents the factory method that will be invoked to inject the bean.
2. factory-bean: represents the reference of the bean by which factory method will be invoked. It is used
if factory method is non-static.
1. public class A {
2. public static A getA(){//factory method
3. return new A();
4. }
5. }
1) A static factory method that returns instance of its own class. It is used in singleton design pattern.
2) A static factory method that returns instance of another class. It is used instance is not known and decided
at runtime.
3) A non-static factory method that returns instance of another class. It is used instance is not known and
decided at runtime.
AOP breaks the program logic into distinct parts (called concerns). It is used to increase modularity by cross-
cutting concerns.
A cross-cutting concern is a concern that can affect the whole application and should be centralized in one
location in code as possible, such as transaction management, authentication, logging, security etc.
It provides the pluggable way to dynamically add the additional concern before, after or around the actual
logic. Suppose there are 10 methods in a class as given below:
Keep Watching
1. class A{
2. public void m1(){...}
3. public void m2(){...}
4. public void m3(){...}
5. public void m4(){...}
6. public void m5(){...}
7. public void n1(){...}
8. public void n2(){...}
9. public void p1(){...}
10. public void p2(){...}
11. public void p3(){...}
12. }
There are 5 methods that starts from m, 2 methods that starts from n and 3 methods that starts from p.
Understanding Scenario I have to maintain log and send notification after calling methods that starts from m.
Problem without AOP We can call methods (that maintains log and sends notification) from the methods
starting with m. In such scenario, we need to write the code in all the 5 methods.
But, if client says in future, I don't have to send notification, you need to change all the methods. It leads to the
maintenance problem.
Solution with AOP We don't have to call methods from the method. Now we can define the additional
concern like maintaining log, sending notification etc. in the method of a class. Its entry is given in the xml file.
In future, if client says to remove the notifier functionality, we need to change only in the xml file. So,
maintenance is easy in AOP.
o Join point
o Advice
o Pointcut
o Introduction
o Target Object
o Aspect
o Interceptor
o AOP Proxy
o Weaving
Join point
Join point is any point in your program such as method execution, exception handling, field access etc. Spring
supports only method execution join point.
Advice
Advice represents an action taken by an aspect at a particular join point. There are different types of advices:
Pointcut
Introduction
It means introduction of additional method and fields for a type. It allows you to introduce new interface to any
advised object.
Target Object
It is the object i.e. being advised by one or more aspects. It is also known as proxied object in spring because
Spring AOP is implemented using runtime proxies.
Aspect
Interceptor
AOP Proxy
It is used to implement aspect contracts, created by AOP framework. It will be a JDK dynamic proxy or CGLIB
proxy in spring framework.
Weaving
It is the process of linking aspect with other application types or objects to create an advised object. Weaving
can be done at compile time, load time or runtime. Spring AOP performs weaving at runtime.
Spring JdbcTemplate Tutorial
Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It
internally uses JDBC api, but eliminates a lot of problems of JDBC API.
o We need to write a lot of code before and after executing the query, such as creating connection,
statement, closing resultset, connection etc.
o We need to perform exception handling code on the database logic.
o We need to handle transaction.
o Repetition of all these codes from one to another database logic is a time consuming task.
Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides you methods to
write the queries directly, so it saves a lot of work and time.
o JdbcTemplate
o NamedParameterJdbcTemplate
o SimpleJdbcTemplate
o SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class
It is the central class in the Spring JDBC support classes. It takes care of creation and release of resources such
as creating and closing of connection object etc. So it will not lead to any problem if you forget to close the
connection.
It handles the exception and provides the informative exception messages by the help of excepion classes
defined in the org.springframework.dao package.
We can perform all the database operations by the help of JdbcTemplate class such as insertion, updation,
deletion and retrieval of the data from the database.
1) public int update(String query) is used to insert, update and delete records.
2) public int update(String query,Object... args) is used to insert, update and delete records using
PreparedStatement using given arguments.
5) public T query(String sql, ResultSetExtractor rse) is used to fetch records using ResultSetExtractor.
6) public List query(String sql, RowMapper rse) is used to fetch records using RowMapper.
We are assuming that you have created the following table inside the Oracle10g database.
This class contains 3 properties with constructors and setter and getters.
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private float salary;
7. //no-arg and parameterized constructors
8. //getters and setters
9. }
EmployeeDao.java
It contains one property jdbcTemplate and three methods saveEmployee(), updateEmployee and
deleteEmployee().
1. package com.javatpoint;
2. import org.springframework.jdbc.core.JdbcTemplate;
3.
4. public class EmployeeDao {
5. private JdbcTemplate jdbcTemplate;
6.
7. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
8. this.jdbcTemplate = jdbcTemplate;
9. }
10.
11. public int saveEmployee(Employee e){
12. String query="insert into employee values(
13. '"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
14. return jdbcTemplate.update(query);
15. }
16. public int updateEmployee(Employee e){
17. String query="update employee set
18. name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";
19. return jdbcTemplate.update(query);
20. }
21. public int deleteEmployee(Employee e){
22. String query="delete from employee where id='"+e.getId()+"' ";
23. return jdbcTemplate.update(query);
24. }
25.
26. }
applicationContext.xml
The DriverManagerDataSource is used to contain the information about the database such as driver class
name, connnection URL, username and password.
There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we
need to provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource
property.
Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter
method but you can use constructor also.
This class gets the bean from the applicationContext.xml file and calls the saveEmployee() method. You can also
call updateEmployee() and deleteEmployee() method by uncommenting the code as well.
1. package com.javatpoint;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5. public class Test {
6.
7. public static void main(String[] args) {
8. ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
9.
10. EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
11. int status=dao.saveEmployee(new Employee(102,"Amit",35000));
12. System.out.println(status);
13.
14.
15. }
16.
17. }
Spring SimpleJdbcTemplate Example
Spring 3 JDBC supports the java 5 feature var-args (variable argument) and autoboxing by the help of
SimpleJdbcTemplate class.
SimpleJdbcTemplate class wraps the JdbcTemplate class and provides the update method where we can pass
arbitrary number of arguments.
We should pass the parameter values in the update method in the order they are defined in the parameterized query.
We are assuming that you have created the following table inside the Oracle10g database.
This class contains 3 properties with constructors and setter and getters.
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private float salary;
7. //no-arg and parameterized constructors
8. //getters and setters
9. }
EmployeeDao.java
It contains one property SimpleJdbcTemplate and one method update. In such case, update method will update
only name for the corresponding id. If you want to update the name and salary both, comment the above two
lines of code of the update method and uncomment the 2 lines of code given below.
1. package com.javatpoint;
2.
3. import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
4. public class EmpDao {
5. SimpleJdbcTemplate template;
6.
7. public EmpDao(SimpleJdbcTemplate template) {
8. this.template = template;
9. }
10. public int update (Emp e){
11. String query="update employee set name=? where id=?";
12. return template.update(query,e.getName(),e.getId());
13.
14. //String query="update employee set name=?,salary=? where id=?";
15. //return template.update(query,e.getName(),e.getSalary(),e.getId());
16. }
17.
18. }
applicationContext.xml
The DriverManagerDataSource is used to contain the information about the database such as driver class
name, connnection URL, username and password.
There are a property named datasource in the SimpleJdbcTemplate class of DriverManagerDataSource type.
So, we need to provide the reference of DriverManagerDataSource object in the SimpleJdbcTemplate class for
the datasource property.
Here, we are using the SimpleJdbcTemplate object in the EmployeeDao class, so we are passing it by the
constructor but you can use setter method also.
This class gets the bean from the applicationContext.xml file and calls the update method of EmpDao class.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class SimpleTest {
9. public static void main(String[] args) {
10.
11. Resource r=new ClassPathResource("applicationContext.xml");
12. BeanFactory factory=new XmlBeanFactory(r);
13.
14. EmpDao dao=(EmpDao)factory.getBean("edao");
15. int status=dao.update(new Emp(23,"Tarun",35000));
16. System.out.println(status);
17. }
18. }
19. Spring with ORM Frameworks
Spring provides API to easily integrate Spring with ORM frameworks such as Hibernate, JPA(Java Persistence
API), JDO(Java Data Objects), Oracle Toplink and iBATIS.
There are a lot of advantage of Spring framework in respect to ORM frameworks. There are as follows:
o Less coding is required: By the help of Spring framework, you don't need to write extra codes before
and after the actual database logic such as getting the connection, starting transaction, commiting
transaction, closing connection etc.
o Easy to test: Spring's IoC approach makes it easy to test the application.
o Better exception handling: Spring framework provides its own API for exception handling with ORM
framework.
o Integrated transaction management: By the help of Spring framework, we can wrap our mapping
code with an explicit template wrapper class or AOP style method interceptor.
The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like
create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.
As you can see in the code of sole hibernate, you have to follow so many steps.
Now, you don't need to follow so many steps. You can simply write this.
2) Serializable save(Object entity) persists the given object and returns id.
3) void saveOrUpdate(Object entity) persists or updates the given object. If id is found, it updates the record
otherwise saves the record.
5) void delete(Object entity) deletes the given object on the basis of id.
6) Object get(Class entityClass, returns the persistent object on the basis of given id.
Serializable id)
7) Object load(Class entityClass, returns the persistent object on the basis of given id.
Serializable id)
JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application. It is currently
used as the replacement for complex entity beans.
The implementation of JPA specification are provided by many vendors such as:
o Hibernate
o Toplink
o iBatis
o OpenJPA etc.
o
A Spring MVC provides an elegant solution to use MVC in spring framework by the help of DispatcherServlet.
Here, DispatcherServlet is a class that receives the incoming request and maps it to the right resource such as
controllers, models, and views.
o Model - A model contains the data of the application. A data can be a single object or a collection of
objects.
o Controller - A controller contains the business logic of an application. Here, the @Controller
annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format. Generally, JSP+JSTL is used
to create a view page. Although spring also supports other view technologies such as Apache Velocity,
Thymeleaf and FreeMarker.
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as the front controller. It is
responsible to manage the flow of the Spring MVC application.
o Separate roles - The Spring MVC separates each role, where the model object, controller, command
object, view resolver, DispatcherServlet, validator, etc. can be fulfilled by a specialized object.
o Light-weight - It uses light-weight servlet container to develop and deploy your application.
o Powerful Configuration - It provides a robust configuration for both framework and application
classes that includes easy referencing across contexts, such as from web controllers to business objects
and validators.
o Rapid development - The Spring MVC facilitates fast and parallel development.
o Reusable business code - Instead of creating new objects, it allows us to use the existing business
objects.
o Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject test data using
the setter methods.
o Flexible Mapping - It provides the specific annotations that easily redirect the page.
o Load the spring jar files or add dependencies in the case of Maven
o Create the controller class
o Provide the entry of controller in the web.xml file
o Define the bean in the separate XML file
o Display the message in the JSP page
o Start the server and deploy the project
pom.xml
To create the controller class, we are using two annotations @Controller and @RequestMapping.
The @Requestmapping annotation is used to map the class with the specified URL name.
HelloController.java
1. ackage com.javatpoint;
2. import org.springframework.stereotype.Controller;
3. import org.springframework.web.bind.annotation.RequestMapping;
4. @Controller
5. public class HelloController {
6. @RequestMapping("/")
7. public String display()
8. {
9. return "index";
10. }
11. }
In this xml file, we are specifying the servlet class DispatcherServlet that acts as the front controller in Spring
Web MVC. All the incoming request for the html file will be forwarded to the DispatcherServlet.
web.xml
This is the important configuration file where we need to specify the View components.
The context:component-scan element defines the base-package where DispatcherServlet will search the
controller class.
spring-servlet.xml
This is the simple JSP page, displaying the message returned by the Controller.
index.jsp
1. <html>
2. <body>
3. <p>Welcome to Spring MVC Tutorial</p>
4. </body>
5. </html>
Output:
Spring MVC Model Interface
In Spring MVC, the model works a container that contains the data of the application. Here, a data can be in
any form such as objects, strings, information from the database, etc.
It is required to place the Model interface in the controller part of the application. The object
of HttpServletRequest reads the information provided by the user and pass it to the Model interface. Now, a
view page easily accesses the data from the model part.
Method Description
Model addAllAttributes(Collection<?> It adds all the attributes in the provided Collection into this Map.
arg)
Model addAllAttributes(Map<String,?> It adds all the attributes in the provided Map into this Map.
arg)
Model addAllAttribute(Object arg) It adds the provided attribute to this Map using a generated name.
Model addAllAttribute(String arg0, It binds the attribute with the provided name.
Object arg1)
Map<String, Object> asMap() It return the current set of model attributes as a Map.
Model mergeAttributes(Map< String,?> It adds all attributes in the provided Map into this Map, with existing
arg) objects of the same name taking precedence.
boolean containsAttribute(String arg) It indicates whether this model contains an attribute of the given name
Spring Boot Tutorial
Spring Boot Tutorial provides basic and advanced concepts of Spring Framework. Our Spring Boot Tutorial is
designed for beginners and professionals both.
Spring Boot is a Spring module that provides the RAD (Rapid Application Development) feature to the Spring
framework.
Our Spring Boot Tutorial includes all topics of Spring Boot such, as features, project, maven project, starter
project wizard, Spring Initializr, CLI, applications, annotations, dependency management, properties, starters,
Actuator, JPA, JDBC, etc.
It is a Spring module that provides the RAD (Rapid Application Development) feature to the Spring
Framework. It is used to create a stand-alone Spring-based application that you can just run because it needs
minimal Spring configuration.
In short, Spring Boot is the combination of Spring Framework and Embedded Servers.
In Spring Boot, there is no requirement for XML configuration (deployment descriptor). It uses convention over
configuration software design paradigm that means it decreases the effort of the developer.
We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java applications.
Why should we use Spring Boot Framework?
Along with the Spring Boot Framework, many other Spring sister projects help to build applications addressing
modern business needs. There are the following Spring sister projects are as follows:
o Spring Data: It simplifies data access from the relational and NoSQL databases.
o Spring Batch: It provides powerful batch processing.
o Spring Security: It is a security framework that provides robust security to applications.
o Spring Social: It supports integration with social networking like LinkedIn.
o Spring Integration: It is an implementation of Enterprise Integration Patterns. It facilitates integration
with other enterprise applications using lightweight messaging and declarative adapters.
Spring Boot can use dependencies that are not going to be used in the application. These dependencies
increase the size of the application.
By providing or avoiding the above points, Spring Boot Framework reduces Development time, Developer
Effort, and increases productivity.
Spring Boot: Spring Boot is a module of Spring Framework. It allows us to build a stand-alone application with
minimal or zero configurations. It is better to use if we want to develop a simple Spring-based application or
RESTful services.
The primary comparison between Spring and Spring Boot are discussed below:
Spring Framework is a widely used Java EE Spring Boot Framework is widely used to develop REST APIs.
framework for building applications.
It aims to simplify Java EE development that It aims to shorten the code length and provide the easiest way to
makes developers more productive. develop Web Applications.
The primary feature of the Spring The primary feature of Spring Boot is Autoconfiguration. It
Framework is dependency injection. automatically configures the classes based on the requirement.
It helps to make things simpler by allowing It helps to create a stand-alone application with less configuration.
us to develop loosely coupled applications.
To test the Spring project, we need to set Spring Boot offers embedded server such as Jetty and Tomcat, etc.
up the sever explicitly.
It does not provide support for an in- It offers several plugins for working with an embedded and in-
memory database. memory database such as H2.
Developers manually define dependencies Spring Boot comes with the concept of starter in pom.xml file that
for the Spring project in pom.xml. internally takes care of downloading the dependencies JARs based on
Spring Boot Requirement.
Spring Boot vs. Spring MVC
Spring Boot: Spring Boot makes it easy to quickly bootstrap and start developing a Spring-based application. It
avoids a lot of boilerplate code. It hides a lot of complexity behind the scene so that the developer can quickly
get started and develop Spring-based applications easily.
Spring MVC: Spring MVC is a Web MVC Framework for building web applications. It contains a lot of
configuration files for various capabilities. It is an HTTP oriented web application development framework.
Spring Boot and Spring MVC exist for different purposes. The primary comparison between Spring Boot and
Spring MVC are discussed below:
Spring Boot is a module of Spring for packaging the Spring- Spring MVC is a model view controller-based web
based application with sensible defaults. framework under the Spring framework.
It provides default configurations to build Spring- It provides ready to use features for building a web
powered framework. application.
It avoids boilerplate code and wraps dependencies together in It specifies each dependency separately.
a single unit.
It reduces development time and increases productivity. It takes more time to achieve the same.
Spring Boot follows a layered architecture in which each layer communicates with the layer directly below or
above (hierarchical structure) it.
Before understanding the Spring Boot Architecture, we must know the different layers and classes present in
it. There are four layers in Spring Boot are as follows:
o Presentation Layer
o Business Layer
o Persistence Layer
o Database Layer
Presentation Layer: The presentation layer handles the HTTP requests, translates the JSON parameter to
object, and authenticates the request and transfer it to the business layer. In short, it consists of views i.e.,
frontend part.
Business Layer: The business layer handles all the business logic. It consists of service classes and uses services
provided by data access layers. It also performs authorization and validation.
Persistence Layer: The persistence layer contains all the storage logic and translates business objects from
and to database rows.
Database Layer: In the database layer, CRUD (create, retrieve, update, delete) operations are performed.
In this section, we are going to discuss some important Spring Boot Annotation that we will use later in this
tutorial.
Example
Example
1. @Component
2. public class Customer
3. {
4. private Person person;
5. @Autowired
6. public Customer(Person person)
7. {
8. this.person=person;
9. }
10. }
@Configuration: It is a class-level annotation. The class annotated with @Configuration used by Spring
Containers as a source of bean definitions.
Example
1. @Configuration
2. public class Vehicle
3. {
4. @BeanVehicle engine()
5. {
6. return new Vehicle();
7. }
8. }
@ComponentScan: It is used when we want to scan a package for beans. It is used with the annotation
@Configuration. We can also specify the base packages to scan for Spring Components.
Example
1. @ComponentScan(basePackages = "com.javatpoint")
2. @Configuration
3. public class ScanComponent
4. {
5. // ...
6. }
@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a
bean to be managed by Spring Container.
Example
1. @Bean
2. public BeanExample beanExample()
3. {
4. return new BeanExample ();
5. }
1. @Component
2. public class Student
3. {
4. .......
5. }
Example
1. @Controller
2. @RequestMapping("books")
3. public class BooksController
4. {
5. @RequestMapping(value = "/{name}", method = RequestMethod.GET)
6. public Employee getBooksByName()
7. {
8. return booksTemplate;
9. }
10. }
@Service: It is also used at class level. It tells the Spring that class contains the business logic.
Example
1. package com.javatpoint;
2. @Service
3. public class TestService
4. {
5. public void service1()
6. {
7. //business code
8. }
9. }
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the
database directly. The repository does all the operations related to the database.
1. package com.javatpoint;
2. @Repository
3. public class TestRepository
4. {
5. public void delete()
6. {
7. //persistence code
8. }
9. }
1. @Controller
2. public class BooksController
3. {
4. @RequestMapping("/computer-science/books")
5. public String getAllBooks(Model model)
6. {
7. //application code
8. return "bookList";
9. }
o @GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a
web service endpoint that fetches It is used instead of using: @RequestMapping(method =
RequestMethod.GET)
o @PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create
a web service endpoint that creates It is used instead of using: @RequestMapping(method =
RequestMethod.POST)
o @PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a
web service endpoint that creates or updates It is used instead of using: @RequestMapping(method
= RequestMethod.PUT)
o @DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to
create a web service endpoint that deletes a resource. It is used instead of
using: @RequestMapping(method = RequestMethod.DELETE)
o @PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is used
instead of using: @RequestMapping(method = RequestMethod.PATCH)
o @RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it
uses HTTP MessageConverters to convert the body of the request. When we annotate a method
parameter with @RequestBody, the Spring framework binds the incoming HTTP request body to that
parameter.
o @ResponseBody: It binds the method return value to the response body. It tells the Spring Boot
Framework to serialize a return an object into JSON and XML format.
o @PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web
service, where the URL contains a path variable. We can define multiple @PathVariable in a method.
o @RequestParam: It is used to extract the query parameters form the URL. It is also known as a query
parameter. It is most suitable for web applications. It can specify default values if the query parameter
is not present in the URL.
o @RequestHeader: It is used to get the details about the HTTP request headers. We use this
annotation as a method parameter. The optional elements of the annotation are name, required,
value, defaultValue. For each detail in the header, we should specify separate annotations. We can
use it multiple time in a method
o @RestController: It can be considered as a combination
of @Controller and @ResponseBody annotations. The @RestController annotation is itself annotated
with the @ResponseBody annotation. It eliminates the need for annotating each method with
@ResponseBody.
o @RequestAttribute: It binds a method parameter to request attribute. It provides convenient access
to the request attributes from a controller method. With the help of @RequestAttribute annotation, we
can access objects that are populated on the server-side.
Spring Boot AOP
The application is generally developed with multiple layers. A typical Java application has the following layers:
o Web Layer: It exposes the services using the REST or web application.
o Business Layer: It implements the business logic of an application.
o Data Layer: It implements the persistence logic of the application.
The responsibility of each layer is different, but there are a few common aspects that apply to all layers
are Logging, Security, validation, caching, etc. These common aspects are called cross-cutting concerns.
If we implement these concerns in each layer separately, the code becomes more difficult to maintain. To
overcome this problem, Aspect-Oriented Programming (AOP) provides a solution to implement cross-cutting
concerns.
It ensures that the cross-cutting concerns are defined in one cohesive code component.
AOP
AOP (Aspect-Oriented Programming) is a programming pattern that increases modularity by allowing the
separation of the cross-cutting concern. These cross-cutting concerns are different from the main business
logic. We can add additional behavior to existing code without modification of the code itself.
Using AOP, we define common functionality in one place. We are free to define how and where this
functionality is applied without modifying the class to which we are applying the new feature. The cross-cutting
concern can now be modularized into special classes, called aspect.
o First, the logic for each concern is now in one place instead of scattered all over the codebase.
o Second, the business modules only contain code for their primary concern. The secondary concern has
been moved to the aspect.
The aspects have the responsibility that is to be implemented, called advice. We can implement an aspect's
functionality into a program at one or more join points.
Benefits of AOP
Cross-cutting concern
The cross-cutting concern is a concern that we want to implement in multiple places in an application. It affects
the entire application.
AOP Terminology
o Aspect: An aspect is a module that encapsulates advice and pointcuts and provides cross-cutting An
application can have any number of aspects. We can implement an aspect using regular class
annotated with @Aspect annotation.
o Pointcut: A pointcut is an expression that selects one or more join points where advice is executed. We
can define pointcuts using expressions or patterns. It uses different kinds of expressions that matched
with the join points. In Spring Framework, AspectJ pointcut expression language is used.
o Join point: A join point is a point in the application where we apply an AOP aspect. Or it is a specific
execution instance of an advice. In AOP, join point can be a method execution, exception handling,
changing object variable value, etc.
o Advice: The advice is an action that we take either before or after the method execution. The action is
a piece of code that invokes during the program execution. There are five types of advices in the
Spring AOP framework: before, after, after-returning, after-throwing, and around advice. Advices
are taken for a particular join point. We will discuss these advices further in this section.
o Target object: An object on which advices are applied, is called the target object. Target objects are
always a proxied It means a subclass is created at run time in which the target method is overridden,
and advices are included based on their configuration.
o Weaving: It is a process of linking aspects with other application types. We can perform weaving
at run time, load time, and compile time.
Proxy: It is an object that is created after applying advice to a target object is called proxy. The Spring AOP
implements the JDK dynamic proxy to create the proxy classes with target classes and advice invocations.
These are called AOP proxy classes.
AOP vs. OOP
AOP OOP
Aspect: A code unit that encapsulates pointcuts, Class: A code unit that encapsulates methods and attributes.
advices, and attributes.
Pointcut: It defines the set of entry points in which Method signature: It defines the entry points for the
advice is executed. execution of method bodies.
Waver: It constructs code (source or object) with Compiler: It converts source code to object code.
advice.
There is a need for a separate compilation process. It requires the AspectJ compiler.
It can be implemented on beans managed by Spring It can be implemented on all domain objects.
Container.
It supports only method level weaving. It can wave fields, methods, constructors, static initializers,
final class, etc.
Types of AOP Advices
o Before Advice
o After Advice
o Around Advice
o After Throwing
o After Returning
Before Advice: An advice that executes before a join point, is called before advice. We
use @Before annotation to mark an advice as Before advice.
After Advice: An advice that executes after a join point, is called after advice. We use @After annotation to
mark an advice as After advice.
Around Advice: An advice that executes before and after of a join point, is called around advice.
After Throwing Advice: An advice that executes when a join point throws an exception.
After Returning Advice: An advice that executes when a method executes successfully.