Module 4 CSE3151
Module 4 CSE3151
Spring Core
1
Content to be discussed
• Spring Framework
• Spring AOP
• Spring MVC
• Database
• Spring REST API
• Spring Boot REST
2
Spring Framework
• An open source Java platform that provides comprehensive infrastructure
support for developing robust Java applications very easily and very rapidly
• Developed by Rod Johnson in 2003
• First released under the Apache 2.0 license in June 2003.
• Spring framework makes an easy development of JavaEE applications.
• Spring is a lightweight framework.
• It provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc.
• The Spring framework comprises modules such as IOC, AOP, DAO, Context,
ORM, WEB MVC etc.
3
Inversion Of Control (IOC) and
Dependency Injection
• These design patterns 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:
class Employee
{
Address address;
Employee()
{
address=new Address();
}
}
4
• In such cases, there is a dependency between the Employee and Address (tight
coupling).
• In the Inversion of Control scenario, we do this something like this:
class Employee class Employee
{ {
Address address; Address address;
Employee() Employee(Address address){
{ this.address=address;
address=new Address(); }
} }
}
• Thus, IoC makes the code loosely coupled.
• In such case, there is no need to modify the code, if our logic is moved to a new
environment.
5
• In the Spring framework, the IOC container injects the dependency.
• We provide metadata to the IOC container by XML file or annotation.
6
Applications/Advantages of Spring
• POJO Based - Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is
that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet
container such as Tomcat or some commercial product.
• Modular - Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to
worry only about the ones you need and ignore the rest.
• Integration with existing frameworks - Spring does not reinvent the wheel, instead it truly makes use of some of the existing
technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies.
• Testablity - Testing an application written with Spring is simple because environment-dependent code is moved into this
framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data.
• Web MVC - Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks
such as Struts or other over-engineered or less popular web frameworks.
• Central Exception Handling - Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC,
Hibernate, or JDO, for example) into consistent, unchecked exceptions.
• Lightweight - Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is
beneficial for developing and deploying applications on computers with limited memory and CPU resources.
• Transaction management - Spring provides a consistent transaction management interface that can scale down to a local
transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
7
Spring Framework Architecture
8
High Level Architecture This group comprises
applications of Web, Web-
This group comprises of Servlet, Web-Struts and Web-
JDBC, ORM, OXM, JMS Portlet. These modules
and Transaction
provide support to create web
modules. These modules
basically provide application.
support to interact with
the database.
It provides support to setting and
getting property values, method
These modules support
invocation, accessing collections
aspect-oriented
and indexers, named variables,
programming
logical and arithmetic operators,
implementation where you
retrieval of objects by name etc.
can use Advices, Pointcut,
Annotations.
9
Elements of Spring Module
• Test - This layer provides support of testing with JUnit and TestNG.
• 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.
10
IoC Container
• The IoC container is responsible to instantiate, configure and
assemble the objects. The IoC container gets information's from the
XML file and works accordingly.
• The main tasks performed by IoC container are:
1. to instantiate the application class
2. to configure the object
3. to assemble the dependencies between the objects
• There are two types of IoC containers. They are:
1. BeanFactory
2. ApplicationContext
11
IoC Container
Types of IoC containers.
1. BeanFactory
2. ApplicationContext
Main responsibilities: instantiate, configure and assemble the objects.
• The IoC container gets information from the XML file and works accordingly.
The main tasks performed by IoC container are:
1. Instantiate the application class
2. Configure the object
3. Assemble the dependencies between the objects
12
Difference between BeanFactory and the
ApplicationContext
• BeanFactory and ApplicationContext interfaces act as the IoC container.
• The ApplicationContext interface is built on top of the BeanFactory interface.
• It adds more functionality than BeanFactory, such as
1. Simple integration with Spring's AOP
2. Message resource handling
3. Event propagation, application layer-specific context
So it is better to use ApplicationContext than BeanFactory.
13
Using BeanFactory
• Create the instance of XmlBeanFactory class
Resource resource=new ClassPathResource("applicationContext.xml");
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.
14
Using ApplicationContext
• We need to instantiate the ClassPathXmlApplicationContext class to use the
ApplicationContext as given below:
ApplicationContext context = new ClassPathXmlApplicationContext("appl
icationContext.xml");
• The constructor of ClassPathXmlApplicationContext class receives string, so we can
pass the name of the xml file to create the instance of ApplicationContext.
15
Dependency Injection in Spring
• Dependency Injection (DI) is a design pattern that removes the
dependency from the programming code to make it 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
16
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:
• We get the resource(instance of A class) directly by a new keyword.
A obj = new AImpl();
• Another way is the factory method: A obj = A.getA();
• We can get the resource by JNDI (Java Naming Directory Interface) as:
Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");
17
Problems of Dependency Lookup
• Tight coupling The dependency lookup approach makes the code
tightly coupled. If the resource is changed, we need to perform a lot
of modifications in the code.
• Not easy for testing This approach creates a lot of problems while
testing the application, especially in black box testing.
18
Dependency Injection
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}
}
In such cases, the instance of the Address class is provided by an external source
such as an XML file either by constructor or setter method.
19
Two ways to perform Dependency
Injection in Spring framework
1. By Constructor
2. By Setter method
20
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
• primitive and String-based values
• Dependent object (contained object)
• Collection values etc.
21
Injecting primitive and string-based
values
• The simple example to inject primitive and string-based values. We
have created three files here:
• Employee.java
• applicationContext.xml
• Test.java
22
Constructor Injection with
Dependent Object
• If there is HAS-A relationship between the classes, we create the
instance of dependent object (contained object) first then pass it as
an argument of the main class constructor.
• Here, our scenario is Employee HAS-A Address. The Address class
object will be termed as the dependent object.
23
Constructor Injection with Collection
• We can inject collection values by the constructor in the spring
framework.
• There can be used three elements inside the constructor-arg element.
It can be:
1. list
2. set
3. map
• Each collection can have string-based and non-string-based values.
24
Constructor Injection with Map
Example
• In this example, we are using the map as the answer that has an
answer with a posted username. Here, we are using key and value
pair both as a string.
• Like previous examples, it is the example of the forum where
one question can have multiple answers.
25
Constructor Injection with Non-
String Map (having dependent
Object) Example
• In this example, we are using map as the answer that have Answer
and User. Here, we are using key and value pair both as an object.
Answer has its own information such as answerId, answer and
postedDate, User has its own information such as userId, username,
emailId.
• Like previous examples, it is the example of forum where
one question can have multiple answers.
26
Inheriting Bean in
Spring
• By using the parent attribute of bean, we can specify the inheritance
relation between the beans. In such case, parent bean values will be
inherited to the current bean.
• Let's see the simple example to inherit the bean.
27
Dependency Injection by setter
method
• We can inject the dependency by the 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.
28
Injecting primitive and string-based
values by the setter method
<?xml version="1.0" encoding="UTF-8"?>
<beans
<bean id="obj" class=“PU.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Arun</value>
</property>
<property name="city">
<value>ghaziabad</value>
</property>
29
</bean>
Setter Injection
https://www.javatpoint.com/spring-tutorial-setter-injection-with-depen
dent-object
https://www.javatpoint.com/spring-tutorial-setter-injection-with-collec
tion
https://www.javatpoint.com/spring-tutorial-setter-injection-with-map
https://www.javatpoint.com/spring-tutorial-setter-injection-with-map
30
Autowiring in Spring
• Autowiring feature of the spring framework enables you to inject the object dependency
implicitly.
• It internally uses a setter or constructor injection.
• Autowiring can't be used to inject primitive and string values.
• It works with reference only.
Advantage
• It requires less code because we don't need to write the code to inject the dependency explicitly.
Disadvantage
• No control of the programmer.
• It can't be used for primitive and string values.
31
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) constructo The constructor mode injects the dependency by calling the constructor
r of the class. It calls the constructor having large number of parameters.
5) autodetect It is deprecated since Spring 3.
32
AOP
33
Spring AOP - Aspect Oriented
Programming
• 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.
34
• The key unit of modularity in OOP is the class, whereas in AOP the unit of
modularity is the aspect. Dependency Injection helps you decouple your
application objects from each other and AOP helps you decouple cross-
cutting concerns from the objects that they affect. AOP is like triggers in
programming languages such as Perl, .NET, Java, and others.
• Spring AOP module provides interceptors to intercept an application. For
example, when a method is executed, you can add extra functionality
before or after the method execution.
35
Why use AOP?
• It provides a pluggable way to dynamically add the class A{
concern before, after, or around the logic. public void m1(){...}
• Suppose there are 10 methods in a class as given public void m2(){...}
public void m3(){...}
• There are 5 methods that start from m, 2 methods public void m4(){...}
that start from n and 3 methods that start from p. public void m5(){...}
• Understanding Scenario I must maintain a log and public void n1(){...}
send notifications after calling methods starting public void n2(){...}
from m. public void p1(){...}
public void p2(){...}
public void p3(){...}
}
36
Why use AOP?
• Problem without AOP We can call methods (that maintains log and sends notification) from the
methods starting with m. In such a scenario, we need to write the code in all the 5 methods.
• But, if the client says in future, I don’t have to send a notification, you need to change all the
methods. It leads to a 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 notifications etc. in the method of a class. Its
entry is given in the xml file.
• In future, if the client says to remove the notifier functionality, we need to change only in the xml
file. So, maintenance is easy in AOP.
37
Where use AOP?
AOP is mostly used in the following cases:
• To provide declarative enterprise services such as declarative
transaction management.
• It allows users to implement custom aspects.
38
AOP Concepts and Terminology
S.No Terms Description
This is a module which has a set of APIs providing cross-cutting requirements. For example, a
1 Aspect logging module would be called AOP aspect for logging. An application can have any number
of aspects depending on the requirement.
This represents a point in your application where you can plug-in the AOP aspect. You can also
2 Join point say, it is the actual place in the application where an action will be taken using Spring AOP
framework.
This is the actual action to be taken either before or after the method execution. This is an
3 Advice actual piece of code that is invoked during the program execution by Spring AOP framework.
Pointcut This is a set of one or more join points where an advice should be executed. You can specify
4 pointcuts using expressions or patterns as we will see in our AOP examples.
Introductio An introduction allows you to add new methods or attributes to the existing classes.
5 n
Target The object being advised by one or more aspects. This object will always be a proxied object,
6 also referred to as the advised object.
object
Weaving is the process of linking aspects with other application types or objects to create an
7 Weaving advised object. This can be done at compile time, load time, or at runtime.
39
AOP Implementations
1. AspectJ
2. Spring AOP
3. JBoss AOP
40
Types of Advice
Sr.No Advice Description
Run advice before the a method execution.
1 before
Run advice after the method execution, regardless of its outcome.
2 after
after- Run advice after the a method execution only if method completes successfully.
3
returning
Run advice after the a method execution only if method exits by throwing an
4 after- exception.
throwing
around Run advice before and after the advised method is invoked.
5
41
Hierarchy of advice interfaces
42
Spring AOP usage
• Spring AOP can be used by 3 ways given below. But the widely used
approach is Spring AspectJ Annotation Style. The 3 ways to use spring
AOP are given below:
1. By Spring1.2 Old style (dtd based) (also supported in Spring3)
2. By AspectJ annotation-style
3. By Spring XML configuration-style(schema based)
43
Spring1.2 old style AOP (dtd based)
implementation.
• it is supported in spring 3, but it is recommended to use spring aop
with aspectJ that we are going to learn in next page.
• There are 4 types of advices supported in spring1.2 old style aop
implementation.
1. Before Advice it is executed before the actual method call.
2. After Advice it is executed after the actual method call. If method
returns a value, it is executed after returning value.
3. Around Advice it is executed before and after the actual method
call.
4. Throws Advice it is executed if actual method throws exception.
44
Spring MVC
45
Spring - MVC Framework
46
Spring Web Model-View-Controller
• Model - A model contains the data of the application. Data
can be a single object or a collection of objects.
• Controller - A controller contains the business logic of an
application. Here, the @Controller annotation is used to
mark the class as the controller.
• 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.
• Front Controller - In Spring Web MVC, the DispatcherServlet
class works as the front controller. It is responsible for
managing the flow of the Spring MVC application.
47
Understanding the flow of Spring
Web MVC • As displayed in the figure, the
DispatcherServlet intercepts all the
incoming request, that works as the
front controller.
• The DispatcherServlet gets an entry of
handler mapping from the XML file and
forwards the request to the controller.
• The controller returns an object of
ModelAndView.
• The DispatcherServlet checks the entry
of view resolver in the XML file and
invokes the specified view component.
48
Advantages of Spring MVC
Framework
• 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.
• Light-weight - It uses light-weight servlet container to develop and deploy your application.
• 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.
• Rapid development - The Spring MVC facilitates fast and parallel development.
• Reusable business code - Instead of creating new objects, it allows us to use the existing business
objects.
• Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject test data
using the setter methods.
• Flexible Mapping - It provides the specific annotations that easily redirect the page.
49
Required Jar files or Maven
Dependency
• To run this example, you need to load:
50
Methods of Model Interface
Method Description
Model addAllAttributes(Collection<?> arg) It adds all the attributes in the provided
Collection into this Map.
Model addAllAttributes(Map<String,?> arg) It adds all the attributes in the provided Map
into this Map.
Model addAllAttribute(Object arg) It adds the provided attribute to this Map using
a generated name.
Model addAllAttribute(String arg0, Object arg1) It binds the attribute with the provided name.
Map<String, Object> asMap() It return the current set of model attributes as
a Map.
Model mergeAttributes(Map< String,?> arg) It adds all attributes in the provided Map into
this Map, with existing objects of the same
name taking precedence.
boolean containsAttribute(String arg) It indicates whether this model contains an
attribute of the given name
51
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.
52
Difference between Spring and SpringBoot
55
RESTful Web Services -
Introduction
• It does not define the standard message exchange format. We can
build REST services with both XML and JSON.
The important methods of HTTP are:
• GET: It reads a resource.
• PUT: It updates an existing resource.
• POST: It creates a new resource.
• DELETE: It deletes the resource.
56
Example :Social media application
• POST /users: It creates a user.
• GET /users/{id}: It retrieves the detail of a user.
• GET /users: It retrieves the detail of all users.
• DELETE /users: It deletes all users.
• DELETE /users/{id}: It deletes a user.
• GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.
• POST/users/{id}/ posts: It creates a post of the user.
57
HTTP Status code
• 404: RESOURCE NOT FOUND
• 200: SUCCESS
• 201: CREATED
• 401: UNAUTHORIZED
• 500: SERVER ERROR
58
RESTful Service Constraints
• There must be a service producer and service consumer.
• The service is stateless.
• The service result must be cacheable.
• The interface is uniform and exposes resources.
• The service should assume a layered architecture.
59
Advantages of RESTful web services
• RESTful web services are platform-independent.
• It can be written in any programming language and executed on any
platform.
• It provides different data formats like JSON, text, HTML, and XML.
• It is fast in comparison to SOAP because there is no strict specification
like SOAP.
• These are reusable.
• They are language neutral.
60
Initializing a RESTful Web Services
Project with Spring Boot
• Step 1: Download the Spring Tool Suite (STS) from
https://spring.io/tools3/sts/all and extract it.
• Step 2: Launch the STS.
• Step 3: Click on File menu -> New -> Spring Starter Project ->
61
• If the Spring Starter Project is not enlisted, then click on Other at the
bottom of the menu. A dialog box appears on the screen. Type Spring
Starter Project in the Wizards text box and click on the Next button.
62
• Step 4: provide the name, group, and package of the project. We have
provided:
• Name: restful-web-services
• Group: com.javatpoint
• Package: com.javatpoint.server.main
• Click on the Next button.
63
64
Step 5: Choose the Spring Boot
Version 2.1.8.
65
Step 6: We can see the project
structure in the project explorer
window.
66
Step 7:
• Go to the Maven Repository https://mvnrepository.com/ and
add Spring Web MVC, Spring Boot DevTools,
JPA, and H2 dependencies in the pom.xml. After adding the
dependencies, the pom.xml file looks like the following:
• pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> 67
Step 8
• Now open the RestfulWebServicesApplication.java file and Run the
file as Java Application.
package com.javatpoint.server.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication
;
@SpringBootApplication
public class RestfulWebServicesApplication
{
public static void main(String[] args)
{
SpringApplication.run(RestfulWebServicesApplication.class, args);
}
}
It does not perform any service but ensures that the application is 68
Output
69