28.spring 5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 142

SPRING MAKES JAVA MODERN

AKHIL K ANIL
Basics of spring

★ Latest version(stable) : spring 5.3.8


★ Developed by Rod Johnson in 2003
★ Spring makes development of Java EE application easy
★ It is a lightweight framework
★ It can be thought as a framework of framework because it provides
support for various frameworks such as struts, Hibernate,EJB,JSF etc.
★ Spring provides a structure where we find solutions to various
technical problems
★ It contains various modules such as IOC,AOP,DAO,Context, ORM, WEB
MVC etc.
★ The core concepts of spring are IOC and AOP
SPRING 5 FEATURES

1. Support for Java 8, Java 9, Java EE 7, Java EE 8, Servlet 4.0, Bean


Validation 2.0, and JPA 2.2.
2. Improved Logging with new module – spring-jcl.
3. File operations are using NIO 2 streams, hence improved
performance.
4. Support for Reactor 3.1 Flux and Mono as well as RxJava 1.3 and 2.1
as return values from Spring MVC controller methods.
5. Support for Kotlin, Project Lombok, JSON Binding API as an
alternative to Jackson and GSON.
6. Spring WebFlux – Spring getting Reactive.
7. Support for JUnit 5
8. Functional programming support through Kotlin.
SPRING ARCHITECTURE
Core Components

1. The SpEL module provides a powerful expression language for


manipulating objects during execution
2. Context is built on the basis of Beans and Core and allows you to
access any object that is defined in the settings. The key
element of the Context module is the ApplicationContext
interface
3. The Core module provides key parts of the framework including
IoC and DI properties
4. The Bean module is responsible for creating and managing
Spring Beans – is application context structure unit
Inversion of control(ioc)

➢ It is a design pattern which is used to remove dependency from


the programming code
➢ As of the official documentation IoC is also known as
Dependency Injection(DI)
➢ Understanding dependency :
class Employee{
In this case there is
Address address;
dependency between the
Employee(){ Employee and the
address=new Address(); Address(tight coupling).
}

}
In IoC we do,
class Employee{

Address address;

Employee(Address address){

this.address=address;

Thus IOC makes the code loosely coupled.


❖ In spring, IoC container is responsible to inject dependency
Dependency Injection :
The Dependency Injection is a design pattern that removes the dependency of the programs.

Example :

class Employee{
In such case, instance of
Address class is
Address address;
provided by external
Employee(Address address){ source such as XML file
either by constructor or
this.address=address; setter method
}

public void setAddress(Address address){

this.address=address;

}
There are two ways to perform dependency injection in spring :
● By Constructor
● By Setter method
Spring Bean :
In Spring, the objects that form the backbone of your application and that are managed by
the Spring IoC container are called beans. A bean is an object that is instantiated,
assembled, and otherwise managed by a Spring IoC container.

It is the most important part of any Spring application. Spring


ApplicationContext is responsible to initialize the Spring Beans defined in spring
bean configuration file
WEB

1. The Web module provides functions such as downloading files,


creating web application, rest web service etc.
2. Web-MVC contains a Spring MVC implementation for web
applications.
3. Web-Socket provides support for communication between the
client and the server, using Web-Sockets in web applications.
4. Web-Portlet provides MVC implementation with portlet
environment
DATA ACCESS

1. JDBC provides an abstract layer of JDBC and eliminates the need for the
developer to manually register the monotonous code associated with
connecting to the database.
2. Spring ORM provides integration with popular ORMs such as Hibernate,
JDO, which are implementations of JPA.
3. The OXM module is responsible for linking the Object / XML – XMLBeans,
JAXB, etc.
4. The JMS (Java Messaging Service) module is responsible for creating,
sending and receiving messages.
5. Transactions supports transaction management for classes that implement
certain methods and POJOs.
Miscellaneous modules

1. AOP implements aspect-oriented programming and allows using


the entire arsenal of AOP capabilities.
2. The Aspects module provides integration with AspectJ, which is
also a powerful AOP framework.
3. Instrumentation is responsible for supporting class instrumentation
and class loader, which are used in server applications.
4. The Messaging module provides STOMP support.
5. Finally, the Test module provides testing using TestNG or the JUnit
Framework.
AKHIL K ANIL
IOC CONTAINER
● The IoC container is responsible to instantiate, configure and assemble the objects
● The container gets its instructions on what objects to instantiate, configure, and assemble
by reading configuration metadata
● The configuration metadata is represented in XML, Java annotations, or Java code

The responsibilities of IOC container are:


● Instantiating the bean
● Wiring the beans together
● Configuring the beans
● Managing the bean’s entire life-cycle
★ The org.springframework.beans and org.springframework.context
packages are the basis for Spring Framework’s IoC container
★ Spring framework provides two distinct types of containers :
1. BeanFactory container
2. ApplicationContext container
★ BeanFactory is the root interface of Spring IOC container. ApplicationContext
is the child interface of BeanFactory interface that provides Spring AOP features,
i18n etc
★ One main difference between BeanFactory and ApplicationContext is that
BeanFactory only instantiates bean when we call getBean() method while
ApplicationContext instantiates singleton bean when the container is started, It
doesn't wait for getBean() method to be called
Configuration Metadata :
● configuration metadata represents how you, as an application developer, tell the Spring
container to instantiate, configure, and assemble the objects in your application

● Configuration metadata can be supplied in three ways :

1. XML based configuration metadata


2. Annotation based configuration metadata : Introduced in Spring 2.5
3. Java based configuration metadata : Since Spring 3.0
spring.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="..." class="...">

<!-- collaborators and configuration for this bean go here -->

</bean>

<!-- more bean definitions go here -->

</beans>
Instantiating container :
Using BeanFactory -
Resource resource=new ClassPathResource("spring.xml");

BeanFactory factory=new XmlBeanFactory(resource);


Using ApplicationContext -
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Dependencies needed in pom.xml:
★ spring-core
★ spring-context
★ spring-beans
Using the container :
// create and configure beans

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml”);

// retrieve configured instance

Car obj = context.getBean("car", Car.class);

// use configured instance

obj.setBrand(“Audi”);

obj.setYear(2021);

obj.getDetails();
DEPENDENCY INJECTION

Understanding dependency :
Whenever a class A uses another class or interface B, then A depends on B. A cannot carry out it's
work without B, and A cannot be reused without also reusing B. In such a situation the class A is
called the "dependant" and the class or interface B is called the "dependency".
Two classes that uses each other are called "coupled".
❖ 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
❖ In spring DI is a way to achieve IoC
❖ There are two types of dependency injection

1. Constructor-based dependency injection


2. Setter-based dependency injection
Constructor-based dependency injection

● The <constructor-arg> subelement of <bean> is used for constructor injection


In spring.xml :
Example :

<bean id=”car”
class=”...”>

<constructor-arg
ref=”tyre”/>
</bean>

<bean id=”tyre”
class=”...”>
</bean>
Setter-Based dependency injection

● The <property> subelement of <bean> is used for setter injection

Example :
In spring.xml :

<bean id=”car”
class=”...”>
<property
name=”tyre”
ref=”tyre”></prope
rty>
</bean>

<bean id=”tyre”
class=”...”>
</bean>
AUTOWIRING

★ 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 : It requires the less code because we don't need to write the code to inject the
dependency explicitly
★ Disadvantage : No control of programmer, It can't be used for primitive and string values
Autowiring modes :

no It is the default autowiring mode. It means no autowiring by default.

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.

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.

constructor The constructor mode injects the dependency by calling the


constructor of the class. It calls the constructor having large number
of parameters.

autodetect It is deprecated since spring 3.0


Bean overview

Bean definitions :

1. Class
2. Name
3. Scope
4. Constructor arguments
5. Properties
6. Autowiring mode
7. Lazy initialization mode
8. Initialization method
9. Destruction method
Scope :
singleton
(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototype
Scopes a single bean definition to any number of object instances.
request
Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean
created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
application
Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocket
Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
Annotation-based container configuration
★ Annotations used : @Required(deprecated), @Autowired,@Qualifier
★ In order to use, include context namespace and <context:annotation-config/> in
spring.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config/>

</beans>
@Autowired :
➢ Use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration
file
➢ When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType
autowiring on the method
➢ A constructor @Autowired annotation indicates that the constructor should be autowired when creating the
bean, even if no <constructor-arg> elements are used while configuring the bean in XML file

@Qualifier :
➢ There may be a situation when you create more than one bean of the same type and want to wire only one
of them with a property. In such cases, you can use the @Qualifier annotation along with @Autowired to
remove the confusion by specifying which exact bean will be wired
Example :
public class Student{

....

@Autowired

@Qualifier("course")

private Course course;

public Student(Course course) { //constructor injection

this.course = course;

...}
Java based configuration

● Java-based configuration option enables you to write most of your Spring configuration without XML but with the
help of few Java-based annotations
● Annotations used : @Configuration,@Bean,@Component,@ComponentScan(basePackages=””)

Example :

@Configuration
Instead of defining methods that
public class AppConfig { return bean objects, a more
concise approach is to use
@Bean @Component annotation in
classes and to provide
public Student student() { @ComponentScan annotation in
Configuration class
return new Student(course()); }

@Bean

public Course course() {

return new Course(); } }


Main class :
public class SpringApplication

public static void main( String[] args )

AnnotationConfigApplicationContext ctxt = new AnnotationConfigApplicationContext();

ctxt.register(AppConfig.class); ctxt.refresh();

Course course = ctxt.getBean(Course.class);

course.setCid(1); course.setCourseName("JAVA")

Student student = ctxt.getBean(Student.class);

student.setSid(101); student.setSname("Raju");

System.out.println(student);

}
SPRING AOP

AKHIL K ANIL
Aspect oriented programming(aop)

● AOP is a programming paradigm that aims to increase modularity by allowing the


separation of cross-cutting concerns. It does this by adding additional behavior to
existing code without modifying the code itself
● Instead, we can declare the new code and the new behaviors separately
● AOP compliments OOPs in the sense that it also provides modularity. But the key unit of
modularity is aspect than class

Modular Programming allows development to


be divided by splitting down a program into
smaller programs in order to execute a
variety of tasks.
❖ In Object Oriented Programming, modularity of application is achieved by Classes whereas in Aspect
Oriented Programming application modularity is achieved by Aspects and they are configured to cut
across different classes
❖ 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 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

class A{

public void m1(){...}

public void m2(){...}

public void m3(){...}

public void m4(){...}

public void m5(){...}

public void n1(){...}

public void n2(){...}

public void p1(){...}

public void p2(){...}

public void p3(){...}

}
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. 🥳
AOP Concepts and Terminology Aspect: An aspect is a class that implements
enterprise application concerns that cut across
multiple classes, such as transaction
management. Aspects can be a normal class
configured through Spring XML configuration

Advice : It is the action taken by an aspect at a


particular join-point

Joinpoint: is a point of execution of the


program, such as the execution of a method or
the handling of an exception. In Spring AOP, a
joinpoint always represents a method execution

Pointcut: is a predicate or expression that


matches join points

Advice is associated with a pointcut


expression and runs at any join point
matched by the pointcut.
AOP Advice Types :
1. Before Advice: These advices runs before the execution of join point methods
2. After (finally) Advice: An advice that gets executed after the join point method finishes executing,
whether normally or by throwing an exception
3. After Returning Advice: Sometimes we want advice methods to execute only if the join point method
executes normally
4. After Throwing Advice: This advice gets executed only when join point method throws exception, we
can use it to rollback the transaction declaratively.
5. Around Advice: This is the most important and powerful advice. This advice surrounds the join point
method and we can also choose whether to execute the join point method or not. We can write
advice code that gets executed before and after the execution of the join point method. It is the
responsibility of around advice to invoke the join point method and return values if the method is
returning something
PROJECT STRUCTURE
spring AOP:
<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop

https://www.springframework.org/schema/aop/spring-aop.xsd">
Additional dependencies needed :
<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

<version>5.3.13</version>

</dependency>

<dependency>

<groupId>org.aspectj</groupId>

<artifactId>aspectjweaver</artifactId>

<version>1.9.6</version>

<scope>runtime</scope>

</dependency>
● <dependency>
● <groupId>org.aspectj</groupId>
● <artifactId>aspectjrt</artifactId>
● <version>1.6.11</version>
● </dependency>
Schema based AOP(configurations in XML)
In spring.xml :
<bean id=”employeeManager” class=”package.EmployeeManager”></bean>

<bean id=”aspectClass” class=”package.EmployeeCRUDAspect”></bean>

<aop:config>

<aop:aspect ref=”aspectClass”>

<aop:pointcut id=”ptcut”
expression=”execution(*package.EmployeeManager.getEmployeeById(..))”/>

<aop:before pointcut-ref=”ptcut” method=”logMethod”/>

</aop:aspect>

</aop:config>
Understanding AspectJ pointcut expression
➔ A pointcut expression starts with a pointcut designator (PCD), which is a keyword telling
Spring AOP what to match
➔ The primary Spring PCD is execution, which matches method execution join points
@Pointcut("execution(public Employee package.EmployeeDao.findById(Integer))")

➔ This example pointcut will match exactly the execution of findById method of the
EmployeeDao class. This works, but it is not very flexible
➔ Suppose we would like to match all the methods of the EmployeeDao class, which may
have different signatures, return types, and arguments. To achieve this we may use
wildcards :
@Pointcut("execution(* package.EmployeeDao.*(..))")

➔ Here the first wildcard matches any return value, the second matches any method name,
and the (..) pattern matches any number of parameters (zero or more)
@AspectJ support

❖ @AspectJ refers to a style of declaring aspects as regular Java classes annotated with
annotations
❖ The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5 release
❖ The @AspectJ support can be enabled with XML- or Java-style configuration
❖ In either case, you also need to ensure that AspectJ’s aspectjweaver.jar
❖ To enable @AspectJ support with Java @Configuration, add the @EnableAspectJAutoProxy
annotation
❖ To enable @AspectJ support with XML-based configuration, use the aop:aspectj-autoproxy

element
SpEL(Spring Expression
Language)

AKHIL K ANIL
SpEL is an expression language supporting the features of querying and
manipulating an object graph at runtime
SpEL API :

● Expression interface
Implementati
● SpelExpression class on of
Expression
● ExpressionParser interface Implementation of
ExpressionParser
● SpelExpressionParser class
● EvaluationContext interface Implementation of
EvaluationContext
● SimpleEvaluationContext class
● StandardEvaluationContext class
Evaluation
ExpressionParser expressionParser = new SpelExpressionParser();

// 1. Literal expression

Expression expression = expressionParser.parseExpression("'Hello World'");

String msg = expression.getValue(String.class);

// 2. Method invocation

expression = expressionParser.parseExpression("'Hello World'.concat('!')");

String str = expression.getValue(String.class);

// 3. Mathematical operator

expression = expressionParser.parseExpression("16 * 5");

Integer intVal = expression.getValue(Integer.class);


// 4. Relational operator

expression = expressionParser.parseExpression("5 < 9");

boolean boolVal = expression.getValue(Boolean.class);

// 5. Logical operator

expression = expressionParser.parseExpression("400 > 200 && 200 < 500");

boolVal = expression.getValue(Boolean.class);

// 8. Regex/matches operator

expression = expressionParser.parseExpression("'UPPERCASE STRING' matches '[A-Z\\s]+'");

boolVal = expression.getValue(Boolean.class);

Now, we have evaluated the SpEL expression using the default context.
❖ SpEL expressions can be evaluated against a specific object instance, which is
often mentioned as the root object
❖ Define a Bean and use it as the context of the evaluation

@Component(“sampleBean”)
public class SampleBean(){
private String property = “String property“;
private ArrayList<Integer> arrayList = new ArrayList<>();
public SampleBean(){
arrayList.add(15); arrayList.add(16); arrayList.add(17); }
//getters and setters
}
● Create the evaluation context by creating an instance of StandardEvaluationContext
● It takes the root object ( SampleBean in our case) as a parameter in it’s constructor
Example :
The creation of the
ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationCon
text instance is expensive.
// creating evaluation context So, we should cache and
reuse them as much as
SampleBean ctxtBean = new SampleBean(); possible
StandardEvaluationContext testContext = new StandardEvaluationContext(ctxtBean);
// Property value
Expression expression = parser.parseExpression("property");
String strValue = expression.getValue(testContext,String.class);
// compare property
expression = parser.parseExpression("property == 'String property'");
boolean boolVal = expression.getValue(testContext,Boolean.class);
System.out.println(boolVal);

// List value
expression = parser.parseExpression("arrayList[1]");
int val = expression.getValue(testContext,Integer.class);
System.out.println(val);
SpEL in Bean Definition
@Component("user")
public class User {
@Value("598")
private Integer id;
@Value("John")
private String firstName;
@Value("Doe")
private String lastName;
@Value("#{user.firstName.concat(' ').concat(user.lastName)}")
private String fullName;
//getters and setters
}
DATA ACCESS
USING JDBC

AKHIL K ANIL
JDBC abstraction framework packages

All the classes in Spring JDBC are divided into four separate packages
● core — the core functionality of JDBC. Some of the important classes under this package include
JdbcTemplate, SimpleJdbcInsert, SimpleJdbcCall and NamedParameterJdbcTemplate.
● datasource — utility classes to access a data source. It also has various data source
implementations for testing JDBC code outside the Jakarta EE container.
● object — DB access in an object-oriented manner. It allows running queries and returning the
results as a business object. It also maps the query results between the columns and properties of
business objects.
● support — support classes for classes under core and object packages, e.g., provides the
SQLException translation functionality
JDBCTEMPLATE
➔ JdbcTemplate is the classic and most popular Spring JDBC approach. This “lowest-level” approach and all
others use a JdbcTemplate under the covers
➔ NamedParameterJdbcTemplate wraps a JdbcTemplate to provide named parameters instead of the traditional
JDBC ? placeholders. This approach provides better documentation and ease of use when you have
multiple parameters for an SQL statement
➔ JdbcTemplate is the central class in the JDBC core package. It handles the creation and release of
resources, which helps you avoid common errors, such as forgetting to close the connection

The JdbcTemplate class:

● Runs SQL queries


● Updates statements and stored procedure calls
● Performs iteration over ResultSet instances and extraction of returned parameter values.
● Catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy
defined in the org.springframework.dao package
PROJECT
STRUCTURE
Additional Dependency needed : spring-jdbc
<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>5.3.13</version>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-dbcp2</artifactId>

<version>2.8.0</version>

</dependency>
JdbcConfig.java
Querying Examples :

select
1. Number of rows in a relation :

int rowCount = jdbcTemplate.queryForObject("select count(*) from


user_details", Integer.class);

2. Fetching particular details using id :

String lastName = jdbcTemplate.queryForObject("select last_name from


user_details where uid = ?", String.class, id);
insert,update and delete

3. Inserting new entry :

jdbcTemplate.update("insert into user_details(first_name, last_name)


values (?, ?)",firstName, lastName);

4. Updating existing entry :

jdbcTemplate.update( "update user_details set last_name = ? where


uid = ?", lastName, id);

5. Deleting a entry :

jdbcTemplate.update("delete from user_details where uid = ?",id);


Functional Interface
RowMapper
❏ An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row
basis
❏ Implementations of this interface perform the actual work of mapping each row to a
result object, but don't need to worry about exception handling. SQLExceptions will
be caught and handled by the calling JdbcTemplate
❏ we can use RowMapper interface to fetch the records from the database using query()
method of JdbcTemplate class

Method of RowMapper interface

It defines only one method mapRow that accepts ResultSet instance and int as the parameter
list

syntax - public T mapRow(ResultSet rs, int rowNumber)throws SQLException


Fetching data using RowMapper
queryForObject(query,RowMapper,values)
1. Fetching single object :
User user = jdbcTemplate.queryForObject("select * from user_details where userId=?",

(resultSet, rowNum) ->{

User newUser = new User();

newUser.setUserId(resultSet.getInt(1));

newUser.setFirstName(resultSet.getString(2));

newUser.setLastName(resultSet.getString(3));

newUser.setAge(resultSet.getInt(4));

return newUser;

},userId);
2. Fetching list of domain objects :
String GET_ALL="select * from user_details";

List<User> users = jdbcTemplate.query(GET_ALL,(resultSet,rowNum)->{

User user = new User();

user.setUserId(resultSet.getInt(1));

user.setFirstName(resultSet.getString(2));

user.setLastName(resultSet.getString(3));

user.setAge(resultSet.getInt(4));

return user;

});
Tip for an aspiring developer :

You should use the DriverManagerDataSource class (as


included in the Spring distribution) only for
testing purposes! This variant do not provide
pooling and perform poorly when multiple
requests for a connection are made.

What to use? One option is to use


BasicDataSource. It is the implementation of
javax.sql.DataSource that is configured via JavaBeans
properties. It is available in the package
org.apache.commons.dbcp2
NamedParameterJdbcTemplate
❏ Spring provides another way to insert data by named parameter. In such way, we use names
instead of ?(question mark)

Example :

NamedParameterJdbcTemplate namedParameterJdbcTemplate =

new NamedParameterJdbcTemplate(dataSource);

String sql = "select count(*) from user_details where first_name = :first_name";

SqlParameterSource namedParameters = new MapSqlParameterSource("first_name",


firstName);

int count = namedParameterJdbcTemplate.queryForObject(sql, namedParameters,


Integer.class);

❏ An SqlParameterSource is a source of named parameter values to a NamedParameterJdbcTemplate


❏ The MapSqlParameterSource class is a simple implementation that is an adapter around a
java.util.Map, where the keys are the parameter names and the values are the parameter
values
● Another SqlParameterSource implementation is the BeanPropertySqlParameterSource
class
● This class wraps an arbitrary JavaBean (that is, an instance of a class that
adheres to the JavaBean conventions) and uses the properties of the wrapped
JavaBean as the source of named parameter values

Example :
public int countOfUsers(User user) {

// notice how the named parameters match the properties of the above 'User'
class

String sql = "select count(*) from user_details where first_name = :firstName


and last_name = :lastName";

SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(user);

return namedParameterJdbcTemplate.queryForObject(sql, namedParameters,


Integer.class); }
Spring orm data access
WITH HIBERNATE
WITH JPA

AKHIL K ANIL
SPRING ORM
The Spring Framework supports integration with the Java Persistence API (JPA) and supports native
Hibernate for resource management, data access object (DAO) implementations, and transaction
strategies

Advantage of ORM Frameworks with Spring

● 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, committing transaction, closing connection etc.
● Easy to test: Spring's IoC approach makes it easy to test the application.
● Better exception handling: Spring framework provides its own API for exception
handling with ORM framework.
● 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.
Spring-Hibernate Integration
● 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 spring.xml file(or by using annotations only)
PROJECT STRUCTURE(ANNOTATIONS ONLY)
Steps :
1. Add dependencies to pom.xml

Additional dependencies needed :

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-orm</artifactId>

<version>5.3.13</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.6.0.Final</version>

</dependency>
2. Create Config class
3. Create entity class

Create the entity class and provide javax persistence annotations.

4. Create DAO Layer

a. Dao interface

Define methods

b. Dao implementation class

Annotations used - @Repository

Provide implementations to methods by autowiring SessionFactory(Use


@Autowired)

Use getCurrentSession() of SessionFactory to obtain the current session


5. Create Service Layer
a. Service interface
Define methods
b. Service implementation class
Annotations used - @Service,@Transactional
Provide method implementations by autowiring Dao class(Use @Autowired)
6. Create main class
public class SpringApplication {
public static void main(String[] args) {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
User user = context.getBean(User.class);
user.setFirst_name("John");
user.setLast_name("Doe");
boolean status = userService.addUser(user);
if (status == true) { System.out.println("Success"); }
else { System.out.println("Failed"); }
}
}
Spring-JPA Integration
JPA (Jakarta Persistence API; formerly known as Java Persistence 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:

● Hibernate
● Toplink
● iBatis
● OpenJPA etc.
Code to persist an object using JPA :
EntityManagerFactory emf =
Persistence.createEntityManagerFactory(String persistence-
unit);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(employee); //persisting employee object
em.getTransaction().commit();
Employee e = em.find(Employee.class, 105); //getting
employee object by id
PROJECT STRUCTURE :
Configuration :
DAO
Implementatio
n
main class
AKHIL K ANIL
OVERVIEW

➢ 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
➢ Spring MVC, as many other web frameworks, is designed around the
front controller pattern where a central `, the DispatcherServlet
➢ Here, DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models, and views
➢ The DispatcherServlet, as any Servlet, needs to be declared and mapped
according to the Servlet specification by using Java configuration or in
web.xml
Model - A model contains the data of the
application. A 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.
Front Controller - In Spring Web MVC, the
Although spring also supports other view
DispatcherServlet class works as the front
technologies such as Apache Velocity,
controller. It is responsible to manage the flow of
Thymeleaf and FreeMarker.
the Spring MVC application.
Hello World using Spring MVC- PROJECT
STRUCTURE
STEPS-
1. Add dependencies to pom.xml

spring-context

spring-webmvc

jstl

2. Create an AppConfig class and annotated it with @Configuration, @EnableWebMvc, and


@ComponentScan
Example :
3. Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java

● Configure Spring MVC DispatcherServlet and set up URL mappings to Spring


MVC DispatcherServlet
● Create a SpringMvcDispatcherServletInitializer class by extending the
AbstractAnnotationConfigDispatcherServletInitializer class
4. Model Class - Hello.java

This model data will be rendered on a view (JSP file)

5. Controller Class - HelloWorldController.java

Annotate it with @Controller


6. View - index.jsp

create an helloworld.jsp file under src/main/webapp/WEB-INF/views folder


Spring 5 MVC + Hibernate + JSP

PROJECT
STRUCTURE
1. HibernateConfig.java
2. SpringMVCDispatcherServletInitialize
r.java
3. WebMvcConfig.java
4.
EmployeeController.j
ava
SPRING MVC ANNOTATIONS
❖ @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
❖ @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)
❖ @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)
❖ @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)
❖ @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)
❖ @PatchMapping: It maps the HTTP PATCH requests on the specific
handler method. It is used instead of using: @RequestMapping(method =
RequestMethod.PATCH)
❖ @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.
❖ @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.
❖ @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.
❖ @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
❖ @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.
❖ @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.
AKHIL K ANIL
OVERVIEW
➢ Spring Boot is a project that is built on the top of the Spring Framework
➢ Spring Boot helps you to create stand-alone, production-grade Spring-
based applications that you can run
➢ Spring Boot is a Spring module that provides the RAD (Rapid Application
Development) feature to the Spring framework
➢ It is developed by Pivotal Team and is used to build stand-alone and
production ready spring applications
➢ Latest version : 2.6.1
➢ System requirements : Spring Boot 2.6.1 requires Java 8 and is
compatible up to and including Java 17. Spring Framework 5.3.13 or
above is also required. Maven 3.5+
❖ It is used to create a stand-alone Spring-based application that you can just
run because it needs minimal Spring configuration

❖ 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.
Along with the Spring Boot Framework, many other Spring sister projects help to
build applications addressing modern business needs

● Spring Data: It simplifies data access from the relational and NoSQL
databases.
● Spring Batch: It provides powerful batch processing.
● Spring Security: It is a security framework that provides robust security
to applications.
● Spring Social: It supports integration with social networking like
LinkedIn.
● Spring Integration: It is an implementation of Enterprise Integration
Patterns. It facilitates integration with other enterprise applications using
lightweight messaging and declarative adapters.
ADVANTAGES

★ It creates stand-alone Spring applications that can be started using Java -


jar.
★ 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.
★ It provides opinionated 'starter' POMs to simplify our Maven configuration.
★ It provides production-ready features such as metrics, health checks,
and externalized configuration.
★ There is no requirement for XML configuration
★ 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.
Spring vs Spring Boot
Spring Spring Boot

Spring Framework is a widely used Java EE Spring Boot Framework is widely used to develop
framework for building applications. REST APIs

It aims to simplify Java EE development that makes It aims to shorten the code length and provide the
developers more productive easiest way to develop Web Applications

The primary feature of the Spring Framework is The primary feature of Spring Boot is
dependency injection. Autoconfiguration. It automatically configures the
classes based on the requirement

It helps to make things simpler by allowing us to It helps to create a stand-alone application with less
develop loosely coupled applications configuration.

To test the Spring project, we need to set up the Spring Boot offers embedded server such as Jetty
server explicitly and Tomcat, etc

Developers manually define dependencies for the Spring Boot comes with the concept of starter in
Spring project in pom.xml. pom.xml file that internally takes care of downloading
the dependencies JARs based on Spring Boot
Requirement.
Spring Boot vs Spring MVC

Spring Boot Spring MVC

Spring Boot is a module of Spring for packaging the Spring MVC is a model view controller-based web
Spring-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
powered framework. web application

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

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


descriptor

It avoids boilerplate code and wraps dependencies It specifies each dependency separately
together in a single unit

It reduces development time and increases It takes more time to achieve the same
productivity
ARCHITECTURE
Spring Boot follows a layered architecture in which each layer communicates with the
layer directly below or above (hierarchical structure) it.
There are four layers in Spring Boot are as follows:

● Presentation Layer
● Business Layer
● Persistence Layer
● 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
● Now we have validator classes, view classes, and utility classes.
● 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.
● Creates a data access layer and performs CRUD operation.
● The client makes the HTTP requests (PUT or GET).
● The request goes to the controller, and the controller maps that request and
handles it. After that, it calls the service logic if required.
● In the service layer, all the business logic performs. It performs the logic on
the data that is mapped to JPA with model classes.
● A JSP page is returned to the user if no error occurred.
Spring Initializr
Spring Initializr is a web-based tool provided by the Pivotal Web Service. With the help of Spring
Initializr, we can easily generate the structure of the Spring Boot Project
SPRING BOOT ANNOTATIONS
In addition to the annotations used in Spring Framework Spring boot uses the
following annotations :

● @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.
● @SpringBootApplication: It is a combination of three annotations
@EnableAutoConfiguration, @ComponentScan, and @Configuration.

@SpringBootApplication=@ComponentScan+@EnableAutoConfiguration+@Configuration
Why SPRING BOOT?
★ Spring Boot manages dependencies and configuration
automatically.
★ We need not to specify the version of the dependencies in our
configuration. Spring Boot manages itself. Spring Boot
upgrades all dependencies automatically in a consistent way
when we update the Spring Boot version
★ Each Spring Boot application includes an embedded server.
Embedded server is embedded as a part of deployable
application. The advantage of embedded server is, we do not
require pre-installed server in the environment. With Spring
Boot, default embedded server is Tomcat
Application properties

Spring Boot Framework comes with a built-in


mechanism for application configuration using a file
called application.properties. It is located inside the
src/main/resources folder
Starters
❏ Spring Boot provides a number of starters that allow us to add jars in the
classpath. Spring Boot built-in starters make development easier and rapid.
Spring Boot Starters are the dependency descriptors
❏ In the Spring Boot Framework, all the starters follow a similar naming
pattern: spring-boot-starter-*, where * denotes a particular type of
application. For example, if we want to use Spring and JPA for database
access, we need to include the spring-boot-starter-data-jpa dependency
in our pom.xml file

starter-parent
❏ The spring-boot-starter-parent is a project starter. It provides default
configurations for our applications. It is used internally by all dependencies.
All Spring Boot projects use spring-boot-starter-parent as a parent in
pom.xml file
starter-web
There are two important features of spring-boot-starter-web:

● It is compatible for web development


● Auto configuration

Starter of Spring web uses Spring MVC, REST and Tomcat as a default embedded
server

Spring Data JPA

Spring Data is a high-level Spring Source project. Its purpose is to unify and easy
access to the different kinds of persistence stores, both relational database
systems, and NoSQL data stores
There are three main features of Spring Data JPA are as follows:

● No-code repository: It is the most popular persistence-related pattern. It enables us


to implement our business code on a higher abstraction level.
● Reduced boilerplate code: It provides the default implementation for each method
by its repository interfaces. It means that there is no longer need to implement read
and write operations.
● Generated Queries: Another feature of Spring Data JPA is the generation of
database queries based on the method name. If the query is not too complex, we
need to define a method on our repository interface with the name that starts with
findBy

Eg :

public interface StudentRepository extends CrudRepository<Student, Long>

{
Spring Data Repository :
Spring Data JPA provides three repositories are as follows:

● CrudRepository: It offers standard create, read, update, and delete It


contains method like findOne(), findAll(), save(), delete(), etc.
● PagingAndSortingRepository: It extends the CrudRepository and adds
the findAll methods. It allows us to sort and retrieve the data in a
paginated way.
● JpaRepository: It is a JPA specific repository It is defined in Spring Data
Jpa. It extends the both repository CrudRepository and
PagingAndSortingRepository. It adds the JPA-specific methods, like flush() to
trigger a flush on the persistence context
starter-data-jpa

Spring Boot provides spring-boot-starter-data-jpa dependency to connect Spring


application with relational database efficiently. The spring-boot-starter-data-jpa internally
uses the spring-boot-jpa dependency (since Spring Boot version 1.5.3)

starter-actuator

Spring Boot Actuator is a sub-project of the Spring Boot Framework

It includes a number of additional features that help us to monitor and manage the Spring
Boot application

It contains the actuator endpoints (the place where the resources live). We can use HTTP
and JMX endpoints to manage and monitor the Spring Boot application. If we want to get
production-ready features in an application, we should use the Spring Boot actuator
Spring Boot DevTools

Spring Boot 1.3 provides another module called Spring Boot DevTools. DevTools stands for
Developer Tool

The aim of the module is to try and improve the development time while working with the
Spring Boot application. Spring Boot DevTools pick up the changes and restart the
application

Spring Boot DevTools provides the following features:

● Property Defaults
● Automatic Restart
● LiveReload
● Remote Debug Tunneling
● Remote Update and Restart
SPRING BOOT HELLO WORLD(REST) - EXAMPLE
No additional dependencies needed
HelloController.java
SPRING BOOT HELLO WORLD(WEB APPLICATION) - EXAMPLE
Additional Dependencies :
To view jsp pages the following dependency is needed
<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

Add devtools for development


<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

<optional>true</optional>

</dependency>
● application.properties

spring.mvc.view.prefix:/WEB-INF/jsp/
spring.mvc.view.suffix:.jsp

● Create folder - WEB-INF/jsp inside webapp and create welcome.jsp


● HelloController.java
SPRING BOOT CRUD APPLICATION
SPRING BOOT+SPRING DATA JPA+SPRING MVC+JSP

Project Structure :
Dependencies needed:

★ spring-boot-starter-data-jpa
★ spring-boot-starter-web
★ mysql-connector-java
★ spring-boot-starter-tomcat
★ tomcat-embed-jasper
★ jstl
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/productdb-spboot

spring.datasource.username=root

spring.datasource.password =root

spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

spring.jpa.show-sql=true

spring.mvc.view.prefix=/WEB-INF/jsp/

spring.mvc.view.suffix=.jsp
QUERY METHODS
● The JPA module supports defining a query manually as a String or having it being
derived from the method name
● you can either use JPA named queries through a naming convention (
Using JPA Named Queries) or rather annotate your query method with @Query

Query creation from method names


public interface UserRepository extends Repository<User, Long> {

List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);

this translates into the following query: select u from User u where u.emailAddress = ?
1 and u.lastname = ?2
THE END

AKHIL K ANIL

You might also like