Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Spring Framework

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.

It is helpful for beginners and experienced persons.

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.

Inversion Of Control (IOC) and Dependency Injection


These are the design patterns that are used to remove dependency from the programming code. They make
the code easier to test and maintain. Let's understand this with the following code:

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.

Advantage of Dependency Injection


o makes the code loosely coupled so easy to maintain
o makes the code easy to test

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:

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

The Spring applications are loosely coupled because of dependency injection.

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

This layer provides support of testing with JUnit and TestNG.

Spring Core Container

The Spring Core container contains core, beans, context and expression language (EL) modules.
Core and Beans

These modules provide IOC and Dependency Injection features.

Context

This module supports internationalization (I18N), EJB, JMS, Basic Remoting.

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.

AOP, Aspects and Instrumentation

These modules support aspect oriented programming implementation where you can use Advices, Pointcuts
etc. to decouple the code.

The aspects module provides support to integration with AspectJ.

The instrumentation module provides support to class instrumentation and classloader implementations.

Data Access / Integration

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:

o to instantiate the application class


o to configure the object
o to assemble the dependencies between the objects

There are two types of IoC containers. They are:


1. BeanFactory
2. ApplicationContext

Difference between BeanFactory and the ApplicationContext

The org.springframework.beans.factory.BeanFactory and the


org.springframework.context.ApplicationContext interfaces acts as the IoC container. The ApplicationContext
interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as
simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application
layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext
than BeanFactory.

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:

1. Resource resource=new ClassPathResource("applicationContext.xml");


2. BeanFactory factory=new XmlBeanFactory(resource);

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

The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface. We need


to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext as given below:

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:

1. A obj = new AImpl();

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:

1. Context ctx = new InitialContext();


2. Context environmentCtx = (Context) ctx.lookup("java:comp/env");
3. A obj = (A)environmentCtx.lookup("A");

There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.

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.

Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency

o By Constructor
o By Setter method

Dependency Injection by Constructor Example


We can inject the dependency by constructor. The <constructor-arg> subelement of <bean> is used for
constructor injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values

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.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="e" class="com.javatpoint.Employee">
10. <constructor-arg value="10" type="int"></constructor-arg>
11. </bean>
12.
13. </beans>
Test.java

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

Injecting string-based values

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

You may also pass the string literal as following:

1. ....
2. <bean id="e" class="com.javatpoint.Employee">
3. <constructor-arg value="Sonoo"></constructor-arg>
4. </bean>
5. ....
Output: 0 Sonoo

Dependency Injection by setter method


We can inject the dependency by setter method also. The <property> subelement of <bean> is used for
setter injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values by setter method

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.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="obj" class="com.javatpoint.Employee">
10. <property name="id">
11. <value>20</value>
12. </property>
13. <property name="name">
14. <value>Arun</value>
15. </property>
16. <property name="city">
17. <value>ghaziabad</value>
18. </property>
19.
20. </bean>
21.
22. </beans>
Test.java

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

Output:20 Arun Ghaziabad

Difference between constructor and setter injection


There are many key differences between constructor injection and setter injection.

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:

No. Mode Description

1) no It is the default autowiring mode. It means no autowiring bydefault.

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.

5) autodetect It is deprecated since Spring 3.


Dependency Injection with Factory Method in Spring
Spring framework provides facility to inject bean using factory method. To do so, we can use two attributes of
bean element.

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.

A method that returns instance of a class is called factory method.

1. public class A {
2. public static A getA(){//factory method
3. return new A();
4. }
5. }

Factory Method Types


There can be three types of factory method:

1) A static factory method that returns instance of its own class. It is used in singleton design pattern.

<bean id="a" class="com.javatpoint.A" factory-method="getA"></bean>

2) A static factory method that returns instance of another class. It is used instance is not known and decided
at runtime.

<bean id="b" class="com.javatpoint.A" factory-method="getB"></bean>

3) A non-static factory method that returns instance of another class. It is used instance is not known and
decided at runtime.

<bean id="a" class="com.javatpoint.A"></bean>


<bean id="b" class="com.javatpoint.A" factory-method="getB" factory-bean="a"></bean>
Spring AOP Tutorial
Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides modularity. But the
key unit of modularity is aspect than class.

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.

Why use AOP?

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.

Where use AOP?

AOP is mostly used in following cases:

o to provide declarative enterprise services such as declarative transaction management.


o It allows users to implement custom aspects.

AOP Concepts and Terminology


AOP concepts and terminologies are as follows:

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:

o Before Advice: it executes before a join point.


o After Returning Advice: it executes after a joint point completes normally.
o After Throwing Advice: it executes if method exits by throwing an exception.
o After (finally) Advice: it executes after a join point regardless of join point exit whether normally or
exceptional return.
o Around Advice: It executes before and after a join point.

Pointcut

It is an expression language of AOP that matches join points.

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

It is a class that contains advices, joinpoints etc.

Interceptor

It is an aspect that contains only one advice.

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.

Problems of JDBC API

The problems of JDBC API are as follows:

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.

Advantage of Spring JdbcTemplate

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.

Spring Jdbc Approaches


Spring framework provides following approaches for JDBC database access:

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.

Let's see the methods of spring JdbcTemplate class.


No. Method Description

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.

3) public void execute(String query) is used to execute DDL query.

4) public T execute(String sql, executes the query by using PreparedStatement callback.


PreparedStatementCallback action)

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.

Example of Spring JdbcTemplate

We are assuming that you have created the following table inside the Oracle10g database.

1. create table employee(


2. id number(10),
3. name varchar2(100),
4. salary number(10)
5. );
Employee.java

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.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
10. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
11. <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
12. <property name="username" value="system" />
13. <property name="password" value="oracle" />
14. </bean>
15.
16. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
17. <property name="dataSource" ref="ds"></property>
18. </bean>
19.
20. <bean id="edao" class="com.javatpoint.EmployeeDao">
21. <property name="jdbcTemplate" ref="jdbcTemplate"></property>
22. </bean>
23.
24. </beans>
Test.java

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.

Syntax of update method of SimpleJdbcTemplate class


1. int update(String sql,Object... parameters)

We should pass the parameter values in the update method in the order they are defined in the parameterized query.

Example of SimpleJdbcTemplate class

We are assuming that you have created the following table inside the Oracle10g database.

1. create table employee(


2. id number(10),
3. name varchar2(100),
4. salary number(10)
5. );
Employee.java

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.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
10. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
11. <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
12. <property name="username" value="system" />
13. <property name="password" value="oracle" />
14. </bean>
15.
16. <bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
17. <constructor-arg ref="ds"></constructor-arg>
18. </bean>
19.
20. <bean id="edao" class="com.javatpoint.EmpDao">
21. <constructor-arg>
22. <ref bean="jtemplate"/>
23. </constructor-arg>
24. </bean>
25.
26. </beans>
SimpleTest.java

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.

Advantage of ORM Frameworks with Spring

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.

Hibernate and Spring Integration


We can simply integrate hibernate application with spring application.In hibernate framework, we provide all
the database information hibernate.cfg.xml file.But if we are going to integrate the hibernate application with
spring, we don't need to create the hibernate.cfg.xml file. We can provide all the information in the
applicationContext.xml file.

Advantage of Spring framework with hibernate

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.

So it saves a lot of code.

Understanding problem without using spring:

Let's understand it by the code of hibernate given below:


1. //creating configuration
2. Configuration cfg=new Configuration();
3. cfg.configure("hibernate.cfg.xml");
4.
5. //creating seession factory object
6. SessionFactory factory=cfg.buildSessionFactory();
7.
8. //creating session object
9. Session session=factory.openSession();
10.
11. //creating transaction object
12. Transaction t=session.beginTransaction();
13.
14. Employee e1=new Employee(111,"arun",40000);
15. session.persist(e1);//persisting the object
16.
17. t.commit();//transaction is commited
18. session.close();

As you can see in the code of sole hibernate, you have to follow so many steps.

Solution by using HibernateTemplate class of Spring Framework:

Now, you don't need to follow so many steps. You can simply write this.

1. Employee e1=new Employee(111,"arun",40000);


2. hibernateTemplate.save(e1);
Methods of HibernateTemplate class

No. Method Description

1) void persist(Object entity) persists the given object.

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.

4) void update(Object entity) updates the given object.

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)

8) List loadAll(Class entityClass) returns the all the persistent objects.

Spring Data JPA Tutorial


Spring Data JPA API provides JpaTemplate class to integrate spring application with JPA.

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

Advantage of Spring JpaTemplate


You don't need to write the before and after code for persisting, updating, deleting or searching object such as
creating Persistence instance, creating EntityManagerFactory instance, creating EntityTransaction instance,
creating EntityManager instance, commiting EntityTransaction instance and closing EntityManager.
Spring MVC Tutorial
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller
design pattern. It implements all the basic features of a core spring framework like Inversion of Control,
Dependency Injection.

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.

Spring Web Model-View-Controller

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.

Understanding the flow of Spring Web MVC


o As displayed in the figure, all the incoming request is intercepted by the DispatcherServlet that works
as the front controller.
o The DispatcherServlet gets an entry of handler mapping from the XML file and forwards the request to
the controller.
o The controller returns an object of ModelAndView.
o The DispatcherServlet checks the entry of view resolver in the XML file and invokes the specified view
component.

Advantages of Spring MVC Framework


Let's see some of the advantages of Spring MVC Framework:-

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.

Spring Web MVC Framework Example


Let's see the simple example of a Spring Web MVC framework. The steps are as follows:

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

1. Provide project information and configuration in the pom.xml file.

pom.xml

1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-


instance"
2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3. <modelVersion>4.0.0</modelVersion>
4. <groupId>com.javatpoint</groupId>
5. <artifactId>SpringMVC</artifactId>
6. <packaging>war</packaging>
7. <version>0.0.1-SNAPSHOT</version>
8. <name>SpringMVC Maven Webapp</name>
9. <url>http://maven.apache.org</url>
10. <dependencies>
11. <dependency>
12. <groupId>junit</groupId>
13. <artifactId>junit</artifactId>
14. <version>3.8.1</version>
15. <scope>test</scope>
16. </dependency>
17.
18. <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
19. <dependency>
20. <groupId>org.springframework</groupId>
21. <artifactId>spring-webmvc</artifactId>
22. <version>5.1.1.RELEASE</version>
23. </dependency>
24.
25. <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
26. <dependency>
27. <groupId>javax.servlet</groupId>
28. <artifactId>servlet-api</artifactId>
29. <version>3.0-alpha-1</version>
30. </dependency>
31.
32. </dependencies>
33. <build>
34. <finalName>SpringMVC</finalName>
35. </build>
36. </project>

2. Create the controller class

To create the controller class, we are using two annotations @Controller and @RequestMapping.

The @Controller annotation marks this class as Controller.

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

3. Provide the entry of controller in the web.xml file

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

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee ht
tp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
3. <display-name>SpringMVC</display-name>
4. <servlet>
5. <servlet-name>spring</servlet-name>
6. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
7. <load-on-startup>1</load-on-startup>
8. </servlet>
9. <servlet-mapping>
10. <servlet-name>spring</servlet-name>
11. <url-pattern>/</url-pattern>
12. </servlet-mapping>
13. </web-app>

4. Define the bean in the xml file

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.

This xml file should be located inside the WEB-INF directory.

spring-servlet.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:context="http://www.springframework.org/schema/context"
5. xmlns:mvc="http://www.springframework.org/schema/mvc"
6. xsi:schemaLocation="
7. http://www.springframework.org/schema/beans
8. http://www.springframework.org/schema/beans/spring-beans.xsd
9. http://www.springframework.org/schema/context
10. http://www.springframework.org/schema/context/spring-context.xsd
11. http://www.springframework.org/schema/mvc
12. http://www.springframework.org/schema/mvc/spring-mvc.xsd">
13.
14. <!-- Provide support for component scanning -->
15. <context:component-scan base-package="com.javatpoint" />
16.
17. <!--Provide support for conversion, formatting and validation -->
18. <mvc:annotation-driven/>
19.
20. </beans>

5. Display the message in the JSP page

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.

Methods of Model Interface

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.

What is Spring Boot


Spring Boot is a project that is built on the top of the Spring Framework. It provides an easier and faster way to
set up, configure, and run both simple and web-based applications.

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?

We should use Spring Boot Framework because:

o The dependency injection approach is used in Spring Boot.


o It contains powerful database transaction management capabilities.
o It simplifies integration with other Java frameworks like JPA/Hibernate ORM, Struts, etc.
o It reduces the cost and development time of the application.

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.

Advantages of Spring Boot


o It creates stand-alone Spring applications that can be started using Java -jar.
o It tests web applications easily with the help of different Embedded HTTP servers such as Tomcat,
Jetty, etc. We don't need to deploy WAR files.
o It provides opinionated 'starter' POMs to simplify our Maven configuration.
o It provides production-ready features such as metrics, health checks, and externalized
configuration.
o There is no requirement for XML configuration.
o It offers a CLI tool for developing and testing the Spring Boot application.
o It offers the number of plug-ins.
o It also minimizes writing multiple boilerplate codes (the code that has to be included in many places
with little or no alteration), XML configuration, and annotations.
o It increases productivity and reduces development time.

Limitations of Spring Boot

Spring Boot can use dependencies that are not going to be used in the application. These dependencies
increase the size of the application.

Goals of Spring Boot


The main goal of Spring Boot is to reduce development, unit test, and integration test time.
o Provides Opinionated Development approach
o Avoids defining more Annotation Configuration
o Avoids writing lots of import statements

By providing or avoiding the above points, Spring Boot Framework reduces Development time, Developer
Effort, and increases productivity.

Spring vs. Spring Boot vs. Spring MVC


Spring vs. Spring Boot
Spring: Spring Framework is the most popular application development framework of Java. The main feature of
the Spring Framework is dependency Injection or Inversion of Control (IoC). With the help of Spring
Framework, we can develop a loosely coupled application. It is better to use if application type or
characteristics are purely defined.

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 Spring Boot

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.

The developer writes a lot of code It reduces boilerplate code.


(boilerplate code) to do the minimal task.

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 Spring MVC

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.

There is no need to build configuration manually. It requires build configuration manually.

There is no requirement for a deployment descriptor. A Deployment descriptor is required.

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 Architecture


Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-grade Spring
Based Applications with minimum efforts. It is developed on top of the core Spring Framework.

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.

Spring Boot Flow Architecture


o Now we have validator classes, view classes, and utility classes.
o Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc. The architecture of
Spring Boot is the same as the architecture of Spring MVC, except one thing: there is no need
for DAO and DAOImpl classes in Spring boot.
o Creates a data access layer and performs CRUD operation.
o The client makes the HTTP requests (PUT or GET).
o The request goes to the controller, and the controller maps that request and handles it. After that, it
calls the service logic if required.
o In the service layer, all the business logic performs. It performs the logic on the data that is mapped to
JPA with model classes.
o A JSP page is returned to the user if no error occurred.
Spring Boot Annotations
Spring Boot Annotations is a form of metadata that provides data about a program. In other words, annotations
are used to provide supplemental information about a program. It is not a part of the application that we
develop. It does not have a direct effect on the operation of the code they annotate. It does not change the
action of the compiled program.

In this section, we are going to discuss some important Spring Boot Annotation that we will use later in this
tutorial.

Core Spring Framework Annotations


@Required: It applies to the bean setter method. It indicates that the annotated bean must be populated at
configuration time with the required property, else it throws an exception BeanInitilizationException.

Example

1. public class Machine


2. {
3. private Integer cost;
4. @Required
5. public void setCost(Integer cost)
6. {
7. this.cost = cost;
8. }
9. public Integer getCost()
10. {
11. return cost;
12. }
13. }

@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to


autowire spring bean on setter methods, instance variable, and constructor. When we use @Autowired
annotation, the spring container auto-wires the bean by matching data-type.

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

Spring Framework Stereotype Annotations

@Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java


class annotated with @Component is found during the classpath. The Spring Framework pick
it up and configure it in the application context as a Spring Bean.
Example

1. @Component
2. public class Student
3. {
4. .......
5. }

@Controller: The @Controller is a class-level annotation. It is a specialization


of @Component. It marks a class as a web request handler. It is often used to serve web pages.
By default, it returns a string that indicates which route to redirect. It is mostly used
with @RequestMapping annotation.

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

Spring Boot Annotations


o @EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and
configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release
because developers provided an alternative of the annotation, i.e. @SpringBootApplication.
o @SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration,
@ComponentScan, and @Configuration.

Spring MVC and REST Annotations


o @RequestMapping: It is used to map the web requests. It has many optional elements
like consumes, header, method, name, params, path, produces, and value. We use it with the class
as well as the method.

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.

o Implement the cross-cutting concern as an aspect.


o Define pointcuts to indicate where the aspect has to be applied.

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.

Spring's AOP framework helps us to implement these cross-cutting concerns.

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.

There are two benefits of aspects:

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

o It is implemented in pure Java.


o There is no requirement for a special compilation process.
o It supports only method execution Join points.
o Only run time weaving is available.
o Two types of AOP proxy is available: JDK dynamic proxy and CGLIB proxy.

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.

Advice: It is an implementation of cross-cutting Method bodies: It is an implementation of the business logic


concerns. concerns.

Waver: It constructs code (source or object) with Compiler: It converts source code to object code.
advice.

Spring AOP vs. AspectJ

The differences between AOP and OOP are as follows:

Spring AOP AspectJ

There is a need for a separate compilation process. It requires the AspectJ compiler.

It supports only method execution pointcuts. It supports all pointcuts.

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

There are five types of AOP advices are as follows:

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.

You might also like