SlideShare a Scribd company logo
Slide 1 of 58© People Strategists www.peoplestrategists.com
Spring Framework -III
Slide 2 of 58© People Strategists www.peoplestrategists.com
Objectives
In this session, you will learn to:
Introduce annotation based Configuration
Identifying stereotypes
Explore validation
Introduce Spring DAO Support
Identify advantages of spring over JDBC
Identify Spring JPA
Implement Spring JPA
Integrate Spring with Hibernate
Slide 3 of 58© People Strategists www.peoplestrategists.com
With the advent of Spring 3 there has been an widespread use of
annotations and annotations based configurations.
To turn annotation based configuration on you need to write
<context:annotation-config/> into ApplicationContext.xml.
The following code snippet illustrates how to do annotation based
configuration:
Introducing Annotation Based Configuration
<?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
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-
3.0.xsd">
<context:annotation-config/>
<!-- beans declaration goes here -->
</beans>
Slide 4 of 58© People Strategists www.peoplestrategists.com
Introducing Annotation Bases Configuration (Contd.)
@Value
@PreDestroy@Qualifier
@PostConstruct @Component
@AutoWired
The Spring MVC framework provides following annotations:
Slide 5 of 58© People Strategists www.peoplestrategists.com
Use of @Autowired:
You can implement autowiring by specifiying it in bean classes using the
@Autowired annotation.
To use @Autowired annotation in bean classes, you must first enable the
annotation in spring application using below configuration.
The beans dependencies can be autowired in following three ways:
 @Autowired on properties
 @Autowired on property setters
 @Autowired on constructors
Introducing Annotation Based Configuration (Contd.)
<context:annotation-config/>
OR
<bean class
="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostPr
ocessor"/>
Slide 6 of 58© People Strategists www.peoplestrategists.com
@Autowired on properties:
 It is equivalent to autowiring by byType in configuration file.
 The following code snippet illustrates an example:
Introducing Annotation Based Configuration (Contd.)
public class EmployeeBean
{
@Autowired
private DepartmentBean departmentBean;
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
public void setDepartmentBean(DepartmentBean
departmentBean) {
this.departmentBean = departmentBean;
}
}
Slide 7 of 58© People Strategists www.peoplestrategists.com
@Autowired on property setters:
 It is also equivalent to autowiring by byType in configuration file.
 The following code snippet illustrates an example:
Introducing Annotation Based Configuration (Contd.)
public class EmployeeBean
{
private DepartmentBean departmentBean;
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
@Autowired
public void setDepartmentBean(DepartmentBean
departmentBean) {
this.departmentBean = departmentBean;
}
}
Slide 8 of 58© People Strategists www.peoplestrategists.com
@Autowired on constructors:
 It is equivalent to autowiring by constructor in configuration file.
 The following code snippet illustrates an example:
Introducing Annotation Based Configuration (Contd.)
public class EmployeeBean
{
@Autowired
public EmployeeBean(DepartmentBean departmentBean)
{
this.departmentBean = departmentBean;
}
private DepartmentBean departmentBean;
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
public void setDepartmentBean(DepartmentBean
departmentBean) {
this.departmentBean = departmentBean;
}
}
Slide 9 of 58© People Strategists www.peoplestrategists.com
Use of @Qualifier:
You may have similar properties in two different beans.
In this case, spring will not be able to choose correct bean.
Consider the example:
Introducing Annotation Based Configuration (Contd.)
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<!--First bean of type DepartmentBean-->
<bean id="humanResource" class="com.bean.DepartmentBean">
<property name="name" value="Human Resource" />
</bean>
<!--Second bean of type DepartmentBean-->
<bean id="finance" class="com.bean.DepartmentBean">
<property name="name" value="Finance" />
</bean>
</beans>
Conflict
Slide 10 of 58© People Strategists www.peoplestrategists.com
To avoid the conflict, you can use the @Qualifier annotation along with
@Autowired.
The following code snippet illustrates an example:
Introducing Annotation Based Configuration (Contd.)
public class EmployeeBean
{
@Autowired
@Qualifier("finance")
private DepartmentBean departmentBean;
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
public void setDepartmentBean(DepartmentBean departmentBean) {
this.departmentBean = departmentBean;
}
//More code
}
Specified
Slide 11 of 58© People Strategists www.peoplestrategists.com
Use of @Component:
The @Component annotation marks a java class as a bean.
Use of @Value:
You can also use the @Value annotation to inject values from a property
file into a bean’s attributes.
The following code snippet illustrates an example:
Introducing Annotation Based Configuration (Contd.)
@Component
public class AutowiredFakaSource {
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
public String getDriverClassName() {
return driverClassName;
}
public String getUrl() {
return url;
}
}
Slide 12 of 58© People Strategists www.peoplestrategists.com
Activity: Implementing Autowiring Using byName
Let us see how to implement
@Autowired using byName by
importing the embedded
project in Eclipse.
Slide 13 of 58© People Strategists www.peoplestrategists.com
Activity: Implementing Autowiring Using byType
Let us see how to implement
@Autowired using byType by
importing the embedded
project in Eclipse.
Slide 14 of 58© People Strategists www.peoplestrategists.com
Activity: Implementing Autowiring Using Constructor
Let us see how to implement
@Autowired using constructor
by importing the embedded
project in Eclipse.
Slide 15 of 58© People Strategists www.peoplestrategists.com
Use of @PostConstruct:
@PostConstruct is used for a method in a bean.
The annotated method gets called just after the invocation of constructor.
It can be used perform operations that you need perform before executing
any other method.
Use of @PreDestroy:
@PreDestroy is also used for a method in a bean.
The annotated method gets called just before an object is garbage collected.
It can be used to perform operations at the final moment.
Introducing Annotation Based Configuration (Contd.)
Slide 16 of 58© People Strategists www.peoplestrategists.com
The following code snippet illustrates an example:
Introducing Annotation Based Configuration (Contd.)
package com.customer.services;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class CustomerService
{
String message;
public String getMessage() { return message; }
public void setMessage(String message) {
this.message = message;
}
@PostConstruct
public void init() throws Exception {
System.out.println("Init method after properties are set :" +
message);
}
@PreDestroy
public void cleanUp() throws Exception {
System.out.println("Spring Container is destroy! Customer clean
up");
}
}
Slide 17 of 58© People Strategists www.peoplestrategists.com
The following code snippet configures the bean in spring config file:
Introducing Annotation Based Configuration (Contd.)
<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
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.context.annotation.CommonAnnotationBean
PostProcessor" />
<bean id="customerService"
class="com.customer.services.CustomerService">
<property name="message" value="i'm property message" />
</bean>
</beans>
Slide 18 of 58© People Strategists www.peoplestrategists.com
Activity: Implementing @PreDestroy and @PostConstruct
Let us see how to implement
@PreDestroy and
@PostConstruct.
Slide 19 of 58© People Strategists www.peoplestrategists.com
@Controller
Identifying Stereotypes
@Repository@Service@Component
The Spring MVC framework provides following stereotypes:
With the @Autowired annotation you need to define the beans in the xml
file so that the container is aware of them and can inject them for you.
Spring provides Stereotype annotations that frees you from defining beans
explicitly with XML.
Slide 20 of 58© People Strategists www.peoplestrategists.com
Identifying Stereotypes (Contd.)
The following table describes the various stereotype annotations:
Annotation Description
@Component It is a basic auto component scan
annotation, it indicates annotated class
is a auto scan component.
@Repository You need to use this annotation with in
the persistance layer, which acts like
database repository.
@Service It indicates annotated class is a Service
component in the business layer.
@Controller It is used to create controller
component. It is mainly used at
presentation layer.
Slide 21 of 58© People Strategists www.peoplestrategists.com
Identifying Stereotypes (Contd.)
The following code snippet illustrates an example of
@Controller:
The following code snippet illustrates an example of @Service:
@Controller ("employeeController")
public class EmployeeController
{
@Autowired
EmployeeManager manager;
//use manager
}
@Service ("employeeManager")
public class EmployeeManager{
@Autowired
EmployeeDAO dao;
public EmployeeDTO createNewEmployee(){
return dao.createNewEmployee();
}
}
Slide 22 of 58© People Strategists www.peoplestrategists.com
Identifying Stereotypes (Contd.)
The following code snippet illustrates an example of @Component:
The following code snippet illustrates an example of @Repository:
@Component
public class EmployeeService
{
@Autowired
EmployeeDAO empDAO;
@Override
public String toString() {
return empDAO;
}
}
@Repository ("employeeDao")
public class EmployeeDAO {
public EmployeeDTO createNewEmployee()
{
EmployeeDTO e = new EmployeeDTO();
e.setId(1);
e.setFirstName(“Jack");
e.setLastName(“Mathew");
return e;
}
}
Slide 23 of 58© People Strategists www.peoplestrategists.com
Spring provides validation support to validate the entered value.
It provides a simplified set of APIs and supporting classes for validating
domain objects.
It also allows one to code the validation logic for custom validator.
Introducing Spring Validation Framework
The Spring MVC framework supports following validation
implementation:
Validator
Custom
Validator
Bean Validation
APi
Slide 24 of 58© People Strategists www.peoplestrategists.com
Spring provides the Validator interface to perform validation.
The Validator interface can be used to validate an Object.
It uses Error Object to report any validator error while validating an Object.
The interface is available in the org.springframework.validation
package.
It has following two main methods:
supports(Class):
 Returns a boolean indicating whether or not the target class can be validated by this
validator.
validate(Object, org.springframework.validation.Errors):
 In charge of actually performing validation.
Introducing Spring Validation Framework (Contd.)
Slide 25 of 58© People Strategists www.peoplestrategists.com
The following code snippet shows implementation of the Validator
interface:
Introducing Spring Validation Framework (Contd.)
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
} else if (p.getAge() > 110) {
e.rejectValue("age", "too. old");
}
}
}
Slide 26 of 58© People Strategists www.peoplestrategists.com
Spring provides the several annotations for data validation.
It provides Bean Validation API to validate values of in a form tag.
It has following validation annotation:
@Size
@NotEmpty
@Email
Introducing Spring Validation Framework (Contd.)
Slide 27 of 58© People Strategists www.peoplestrategists.com
The following code snippet declares the model class:
Introducing Spring Validation Framework (Contd.)
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class User {
@NotEmpty
@Email
private String email;
@NotEmpty(message = "Please enter your password.")
@Size(min = 6, max = 15, message = "Your password must between
6 and 15 characters")
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Slide 28 of 58© People Strategists www.peoplestrategists.com
Activity: Implementing the Bean Validation API
Let us see how to implement
validation.
Slide 29 of 58© People Strategists www.peoplestrategists.com
Spring allows you to create custom validator.
You can use Validator interface to implement custom validation.
The following code snippet shows an example:
Introducing Spring Validation Framework (Contd.)
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class StudentValidator implements Validator {
public boolean supports(Class<?> clazz) {
return Student.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
"name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "degree",
"degree.required");
ValidationUtils.rejectIfEmpty(errors, "mark", "mark.required");
ValidationUtils.rejectIfEmpty(errors, "address", "address.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mail",
"mail.required");
Student user = (Student) target;
}
}
Slide 30 of 58© People Strategists www.peoplestrategists.com
Activity: Implementing Custom Validation
Let us see how to implement
custom validation.
Slide 31 of 58© People Strategists www.peoplestrategists.com
The Data Access Object (DAO) support in Spring is aimed at making it
easy to work with database technologies.
It allows one to switch between the aforementioned persistence
technologies fairly easily.
It also allows one to code without worrying about catching exceptions
that are specific to each technology.
Introducing Spring DAO
The Spring MVC framework makes use of the following
components while processing a user request:
JDBC Hibernate JPA JDO
Slide 32 of 58© People Strategists www.peoplestrategists.com
Identifying Advantages of Spring DAO Over JDBC
Advanntage JDBC Spring
Connections Need to explicitly open
and close connections.
Need a separate strategy
for making code reusable
in a variety of
environments.
Uses a DataSource with the
framework managing
connections. Code following
the framework strategy is
automatically reusable.
Exceptions Must catch SQLExceptions
and interpret database
specific SQL error code
or SQL state code.
Framework translates
exceptions to a common
hierarchy based on configurable
translation mappings.
Testing Hard to test standalone
if code uses JNDI lookup
for connection pools.
Can be tested standalone since
a DataSource is easily
configurable for a variety of
environments
Transaction Programmatic transaction
management is possible
but makes code less
reusable in systems with
varying transaction
requirements. CMT
is available for EJBs.
Programmatic or declarativ e
transaction management is
possible. Declarative
transaction management
works with single data source or
JTA without any code changes.
Slide 33 of 58© People Strategists www.peoplestrategists.com
Identifying Spring 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.
Spring supports Java Persistence API (JPA).
Spring JPA is a library / framework that adds an extra layer of abstraction
on the top of our JPA provider.
If you use Spring Data JPA, the repository layer of your application contains
following three layers:
Slide 34 of 58© People Strategists www.peoplestrategists.com
Identifying Spring JPA (Contd.)
Features
of JPA
POJO-based
persistence
model
Support for
enriched
domain
modeling
Expanded
query
language
Standardized
object/relational
mapping
Usable in Java EE
and Java SE
environments
Support for
pluggable
persistence
providers
Inheritance, polymorphism, etc.
Using annotations and/or XML
Slide 35 of 58© People Strategists www.peoplestrategists.com
Identifying Spring JPA (Contd.)
JPA Main
Components
Annotations
Entity
manager
To label artifacts
(classes, methods etc.) for
persistence or persistence
related operations
A “gateway” to the
persistence classes
Allow access to persistent
objects, transaction context,
query language etc.
Slide 36 of 58© People Strategists www.peoplestrategists.com
Identifying Spring JPA (Contd.)
Java Application Java Persistence API
Hibernate TopLink Kodo (OpenJPA)
Everyone can use their own favorite persistence technology
Architecture of JPA.
Slide 37 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA
Download
Hibernate
Components
Prepare Database,
and Download
JDBC Driver
Implemented
POJO entities and
add annotations
Persistence.xml
Implemented
client side code
via EntityManager
Slide 38 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Download Hibernate
Components
Prepare Database, and
Download JDBC Driver
1. Hibernate Core
2. Hibernate EntityManager
3. Hibernate Annotations
http://www.hibernate.org/
MySQL JDBC Driver
http://tinyurl.com/ymt6rb
Slide 39 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Implemented POJO entities and add annotations
Slide 40 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Slide 41 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Configuring Persistence.xml
Entity classes
JDBC Driver
JDBC URL
User name
password
EntityManagerFactory Name
Slide 42 of 58© People Strategists www.peoplestrategists.com
Identifying Spring JPA (Contd.)
JPA uses following annotations:
@Entity: It signifies that a class is persistent and is attached to a class.
@Id: It is an identity to of an entity class. It can be auto generated.
@Column: It is put on getter of a class variable. It has functionalities such as,
Updateable, Nullable, and Length .
For example:
Slide 43 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Entity Manager:
It is a gateway to persistent classes
It enables queries to retrieve records.
It provides transaction facility outside the session beans.
Slide 44 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Implemented client side code via EntityManager
Persistence EntityManagerFactory
EntityManagerDepartment
Create
Create
Operates
Persistence.xml
Slide 45 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Creating Entity:
Slide 46 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Finding an Entity:
Slide 47 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Updating an Entity:
Slide 48 of 58© People Strategists www.peoplestrategists.com
Integrating Spring with Hibernate
The database layer is used to communicate with the relational database,
and provides data persistence.
To access data from a database, you need to implement a tool, such as
Hibernate.
Hibernate is a powerful Object Relation Mapping (ORM) tool that lies
between the database layer and the business layer.
It enables the application to access data from any database and provides
data persistence.
The Spring framework is placed between the application classes and the
ORM tool.
Spring enables you to use its features, such as DI and AOP, to configure
objects in your application.
Therefore, integration of Hibernate with Spring helps you use the
Hibernate objects as Spring beans.
Slide 49 of 58© People Strategists www.peoplestrategists.com
Integrating Spring with Hibernate (Contd.)
RDBMS
Business
Layer
(Spring)
Database
Layer
(Hibernate)
Bean
Management
Declarative Transaction
Management
Hibernate
Integration
Service Beans Business Object
Resource Management DAO Object
Hibernate O/R Mapping Transaction Management
Slide 50 of 58© People Strategists www.peoplestrategists.com
Introducing ORM
Most of the object-oriented applications use relational databases to
store and manage the application data.
The relational databases represent data in a tabular format, whereas
data in object-oriented applications is encapsulated in a class.
You can access a class by using its objects.
However, to access the tabular data, you need to use a query language.
Therefore, it is not possible to directly store the objects in a relational
database.
This difference between the object-oriented and relational database
paradigms is called impedance mismatch.
ORM is a process to map data representations in an object model having
Java data types to a relational data model having SQL data type.
Slide 51 of 58© People Strategists www.peoplestrategists.com
Introducing ORM (Contd.)
It is not possible to directly store the objects in a relational database.
This difference between the object-oriented and relational database
paradigms is called impedance mismatch.
ORM is a process to map data representations in an object model having
Java data types to a relational data model having SQL data type.
Relational Databases Object-oriented
applications
Classes
Tables
Object
Slide 52 of 58© People Strategists www.peoplestrategists.com
Introducing ORM (Contd.)
Configure the
SessionFactory
object in Spring
Access and update
data using Data
Access Object
To integrate
Spring with
Hibernate
Slide 53 of 58© People Strategists www.peoplestrategists.com
Introducing ORM (Contd.)
Configuring the SessionFactory Object in Spring
Create a Spring configuration file
(spring-hibernate.xml)
Declare a session factory by using the
following code snippet:
<bean id="mySessionFactory"
class="org.springframework.orm.hiber
nate4.LocalSessionFactoryBean">
<property name="configLocation"
value="hibernate.cfg.xml"/>
</bean>
Slide 54 of 58© People Strategists www.peoplestrategists.com
Introducing ORM (Contd.)
Accessing and Updating Data Using DAO
Create a DAO class and the
sessionFactory object
using DI
Declare DAO as a bean in
the configuration file
Access DAO class’
methods, similar to other
Spring beans
Slide 55 of 58© People Strategists www.peoplestrategists.com
Introducing ORM (Contd.)
The following code snippet creates a DAO class:
The following code snippet declares it as bean:
The following code snippet accesses the methods of DAO class:
The DAO class:
.....................
public class CourseDetailsDAO {
private SessionFactory sessionFactory;
..................... }
<bean id="courseDetailsDao" class="university.CourseDetailsDAO">
<property name="sessionFactory" ref="mySessionFactory"/> </bean>
ApplicationContext apc=new
ClassPathXmlApplicationContext("university/spring-
hibernate.xml");
CourseDetailsDAO courseDao
=(CourseDetailsDAO)apc.getBean("courseDetailsDao");
Slide 56 of 58© People Strategists www.peoplestrategists.com
Summary
In this session, you learned that:
You can implement autowiring by specifiying it in bean classes using the
@Autowired annotation.
With the @Autowired annotation you need to define the beans in the xml
file so that the container is aware of them and can inject them for you.
Spring provides Stereotype annotations, such as:
 @Component
 @Controller
 @Repository
 @Service
@Component is a basic auto component scan annotation, it indicates
annotated class is a auto scan component.
@Repository is used to signify a persistence layer.
Slide 57 of 58© People Strategists www.peoplestrategists.com
Summary (Contd.)
JPA is the sun specification for persisting objects in the enterprise application.
It is currently used as the replacement for complex entity beans.
If you use Spring Data JPA, the repository layer of your application contains
following three layers:
 Spring Data JPA
 Spring Data Commons
 JPA Provider
The database layer is used to communicate with the relational database, and
provides data persistence.
To access data from a database, you need to implement a tool, such as
Hibernate.
Slide 58 of 58© People Strategists www.peoplestrategists.com
Summary (Contd.)
Hibernate is a powerful Object Relation Mapping (ORM) tool that lies between the
database layer and the business layer.
The Spring framework is placed between the application classes and the ORM tool.
Spring enables you to use its features, such as DI and AOP, to configure objects in
your application.
Ad

More Related Content

What's hot (18)

Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
People Strategists
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
People Strategists
 
TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5
Lokesh Singrol
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
Richard Paul
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6
Lokesh Singrol
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
Lokesh Singrol
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
Lokesh Singrol
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
Lokesh Singrol
 
Spring 2
Spring 2Spring 2
Spring 2
Aruvi Thottlan
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
Syed Shahul
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Struts course material
Struts course materialStruts course material
Struts course material
Vibrant Technologies & Computers
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
Akshay Ballarpure
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
Santosh Kumar Kar
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
Mallikarjuna G D
 
Jdbc
JdbcJdbc
Jdbc
Mallikarjuna G D
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
Richard Paul
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6
Lokesh Singrol
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
Syed Shahul
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
Mallikarjuna G D
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 

Similar to Spring Framework - III (20)

Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring Performance Gains
Spring Performance GainsSpring Performance Gains
Spring Performance Gains
VMware Tanzu
 
PRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docx
PRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docxPRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docx
PRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docx
harrisonhoward80223
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
Zeid Hassan
 
AlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docx
AlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docxAlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docx
AlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docx
galerussel59292
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
Syed Shahul
 
Jsf intro
Jsf introJsf intro
Jsf intro
vantinhkhuc
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
898RakeshWaghmare
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
Saltmarch Media
 
The Anatomy of TYPO3 Sitepackages
The Anatomy of TYPO3 SitepackagesThe Anatomy of TYPO3 Sitepackages
The Anatomy of TYPO3 Sitepackages
Benjamin Kott
 
Krazykoder struts2 spring_hibernate
Krazykoder struts2 spring_hibernateKrazykoder struts2 spring_hibernate
Krazykoder struts2 spring_hibernate
Krazy Koder
 
Synopsis
SynopsisSynopsis
Synopsis
Gaurav Gopal Gupta
 
Spring Boot Loves K8s
Spring Boot Loves K8sSpring Boot Loves K8s
Spring Boot Loves K8s
VMware Tanzu
 
Spring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdfSpring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdf
Patiento Del Mar
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
Majurageerthan Arumugathasan
 
Os Johnson
Os JohnsonOs Johnson
Os Johnson
oscon2007
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting Service
Gunnar Hillert
 
Contexts and Dependency Injection
Contexts and Dependency InjectionContexts and Dependency Injection
Contexts and Dependency Injection
Werner Keil
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring Performance Gains
Spring Performance GainsSpring Performance Gains
Spring Performance Gains
VMware Tanzu
 
PRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docx
PRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docxPRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docx
PRG 420 Week 3 Individual Assignment Netbeans Project (annual co.docx
harrisonhoward80223
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
Zeid Hassan
 
AlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docx
AlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docxAlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docx
AlarmClockAlarmClockAlarmClock.Designer.vbGlobal.Microsoft..docx
galerussel59292
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
Syed Shahul
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
Saltmarch Media
 
The Anatomy of TYPO3 Sitepackages
The Anatomy of TYPO3 SitepackagesThe Anatomy of TYPO3 Sitepackages
The Anatomy of TYPO3 Sitepackages
Benjamin Kott
 
Krazykoder struts2 spring_hibernate
Krazykoder struts2 spring_hibernateKrazykoder struts2 spring_hibernate
Krazykoder struts2 spring_hibernate
Krazy Koder
 
Spring Boot Loves K8s
Spring Boot Loves K8sSpring Boot Loves K8s
Spring Boot Loves K8s
VMware Tanzu
 
Spring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdfSpring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdf
Patiento Del Mar
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting Service
Gunnar Hillert
 
Contexts and Dependency Injection
Contexts and Dependency InjectionContexts and Dependency Injection
Contexts and Dependency Injection
Werner Keil
 
Ad

More from People Strategists (20)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
People Strategists
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
People Strategists
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
People Strategists
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
People Strategists
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
People Strategists
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
People Strategists
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
People Strategists
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
People Strategists
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
People Strategists
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
People Strategists
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
People Strategists
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
People Strategists
 
CSS
CSSCSS
CSS
People Strategists
 
HTML/HTML5
HTML/HTML5HTML/HTML5
HTML/HTML5
People Strategists
 
JDBC
JDBCJDBC
JDBC
People Strategists
 
RDBMS with MySQL
RDBMS with MySQLRDBMS with MySQL
RDBMS with MySQL
People Strategists
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
People Strategists
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
People Strategists
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
People Strategists
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
People Strategists
 
Ad

Recently uploaded (20)

"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 

Spring Framework - III

  • 1. Slide 1 of 58© People Strategists www.peoplestrategists.com Spring Framework -III
  • 2. Slide 2 of 58© People Strategists www.peoplestrategists.com Objectives In this session, you will learn to: Introduce annotation based Configuration Identifying stereotypes Explore validation Introduce Spring DAO Support Identify advantages of spring over JDBC Identify Spring JPA Implement Spring JPA Integrate Spring with Hibernate
  • 3. Slide 3 of 58© People Strategists www.peoplestrategists.com With the advent of Spring 3 there has been an widespread use of annotations and annotations based configurations. To turn annotation based configuration on you need to write <context:annotation-config/> into ApplicationContext.xml. The following code snippet illustrates how to do annotation based configuration: Introducing Annotation Based Configuration <?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 http://www.springframework.org/schema/beans/spring-beans- 3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context- 3.0.xsd"> <context:annotation-config/> <!-- beans declaration goes here --> </beans>
  • 4. Slide 4 of 58© People Strategists www.peoplestrategists.com Introducing Annotation Bases Configuration (Contd.) @Value @PreDestroy@Qualifier @PostConstruct @Component @AutoWired The Spring MVC framework provides following annotations:
  • 5. Slide 5 of 58© People Strategists www.peoplestrategists.com Use of @Autowired: You can implement autowiring by specifiying it in bean classes using the @Autowired annotation. To use @Autowired annotation in bean classes, you must first enable the annotation in spring application using below configuration. The beans dependencies can be autowired in following three ways:  @Autowired on properties  @Autowired on property setters  @Autowired on constructors Introducing Annotation Based Configuration (Contd.) <context:annotation-config/> OR <bean class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostPr ocessor"/>
  • 6. Slide 6 of 58© People Strategists www.peoplestrategists.com @Autowired on properties:  It is equivalent to autowiring by byType in configuration file.  The following code snippet illustrates an example: Introducing Annotation Based Configuration (Contd.) public class EmployeeBean { @Autowired private DepartmentBean departmentBean; public DepartmentBean getDepartmentBean() { return departmentBean; } public void setDepartmentBean(DepartmentBean departmentBean) { this.departmentBean = departmentBean; } }
  • 7. Slide 7 of 58© People Strategists www.peoplestrategists.com @Autowired on property setters:  It is also equivalent to autowiring by byType in configuration file.  The following code snippet illustrates an example: Introducing Annotation Based Configuration (Contd.) public class EmployeeBean { private DepartmentBean departmentBean; public DepartmentBean getDepartmentBean() { return departmentBean; } @Autowired public void setDepartmentBean(DepartmentBean departmentBean) { this.departmentBean = departmentBean; } }
  • 8. Slide 8 of 58© People Strategists www.peoplestrategists.com @Autowired on constructors:  It is equivalent to autowiring by constructor in configuration file.  The following code snippet illustrates an example: Introducing Annotation Based Configuration (Contd.) public class EmployeeBean { @Autowired public EmployeeBean(DepartmentBean departmentBean) { this.departmentBean = departmentBean; } private DepartmentBean departmentBean; public DepartmentBean getDepartmentBean() { return departmentBean; } public void setDepartmentBean(DepartmentBean departmentBean) { this.departmentBean = departmentBean; } }
  • 9. Slide 9 of 58© People Strategists www.peoplestrategists.com Use of @Qualifier: You may have similar properties in two different beans. In this case, spring will not be able to choose correct bean. Consider the example: Introducing Annotation Based Configuration (Contd.) <?xml version="1.0" encoding="UTF-8"?> <beans> <context:annotation-config /> <!--First bean of type DepartmentBean--> <bean id="humanResource" class="com.bean.DepartmentBean"> <property name="name" value="Human Resource" /> </bean> <!--Second bean of type DepartmentBean--> <bean id="finance" class="com.bean.DepartmentBean"> <property name="name" value="Finance" /> </bean> </beans> Conflict
  • 10. Slide 10 of 58© People Strategists www.peoplestrategists.com To avoid the conflict, you can use the @Qualifier annotation along with @Autowired. The following code snippet illustrates an example: Introducing Annotation Based Configuration (Contd.) public class EmployeeBean { @Autowired @Qualifier("finance") private DepartmentBean departmentBean; public DepartmentBean getDepartmentBean() { return departmentBean; } public void setDepartmentBean(DepartmentBean departmentBean) { this.departmentBean = departmentBean; } //More code } Specified
  • 11. Slide 11 of 58© People Strategists www.peoplestrategists.com Use of @Component: The @Component annotation marks a java class as a bean. Use of @Value: You can also use the @Value annotation to inject values from a property file into a bean’s attributes. The following code snippet illustrates an example: Introducing Annotation Based Configuration (Contd.) @Component public class AutowiredFakaSource { @Value("${jdbc.driverClassName}") private String driverClassName; @Value("${jdbc.url}") private String url; public String getDriverClassName() { return driverClassName; } public String getUrl() { return url; } }
  • 12. Slide 12 of 58© People Strategists www.peoplestrategists.com Activity: Implementing Autowiring Using byName Let us see how to implement @Autowired using byName by importing the embedded project in Eclipse.
  • 13. Slide 13 of 58© People Strategists www.peoplestrategists.com Activity: Implementing Autowiring Using byType Let us see how to implement @Autowired using byType by importing the embedded project in Eclipse.
  • 14. Slide 14 of 58© People Strategists www.peoplestrategists.com Activity: Implementing Autowiring Using Constructor Let us see how to implement @Autowired using constructor by importing the embedded project in Eclipse.
  • 15. Slide 15 of 58© People Strategists www.peoplestrategists.com Use of @PostConstruct: @PostConstruct is used for a method in a bean. The annotated method gets called just after the invocation of constructor. It can be used perform operations that you need perform before executing any other method. Use of @PreDestroy: @PreDestroy is also used for a method in a bean. The annotated method gets called just before an object is garbage collected. It can be used to perform operations at the final moment. Introducing Annotation Based Configuration (Contd.)
  • 16. Slide 16 of 58© People Strategists www.peoplestrategists.com The following code snippet illustrates an example: Introducing Annotation Based Configuration (Contd.) package com.customer.services; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class CustomerService { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @PostConstruct public void init() throws Exception { System.out.println("Init method after properties are set :" + message); } @PreDestroy public void cleanUp() throws Exception { System.out.println("Spring Container is destroy! Customer clean up"); } }
  • 17. Slide 17 of 58© People Strategists www.peoplestrategists.com The following code snippet configures the bean in spring config file: Introducing Annotation Based Configuration (Contd.) <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 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBean PostProcessor" /> <bean id="customerService" class="com.customer.services.CustomerService"> <property name="message" value="i'm property message" /> </bean> </beans>
  • 18. Slide 18 of 58© People Strategists www.peoplestrategists.com Activity: Implementing @PreDestroy and @PostConstruct Let us see how to implement @PreDestroy and @PostConstruct.
  • 19. Slide 19 of 58© People Strategists www.peoplestrategists.com @Controller Identifying Stereotypes @Repository@Service@Component The Spring MVC framework provides following stereotypes: With the @Autowired annotation you need to define the beans in the xml file so that the container is aware of them and can inject them for you. Spring provides Stereotype annotations that frees you from defining beans explicitly with XML.
  • 20. Slide 20 of 58© People Strategists www.peoplestrategists.com Identifying Stereotypes (Contd.) The following table describes the various stereotype annotations: Annotation Description @Component It is a basic auto component scan annotation, it indicates annotated class is a auto scan component. @Repository You need to use this annotation with in the persistance layer, which acts like database repository. @Service It indicates annotated class is a Service component in the business layer. @Controller It is used to create controller component. It is mainly used at presentation layer.
  • 21. Slide 21 of 58© People Strategists www.peoplestrategists.com Identifying Stereotypes (Contd.) The following code snippet illustrates an example of @Controller: The following code snippet illustrates an example of @Service: @Controller ("employeeController") public class EmployeeController { @Autowired EmployeeManager manager; //use manager } @Service ("employeeManager") public class EmployeeManager{ @Autowired EmployeeDAO dao; public EmployeeDTO createNewEmployee(){ return dao.createNewEmployee(); } }
  • 22. Slide 22 of 58© People Strategists www.peoplestrategists.com Identifying Stereotypes (Contd.) The following code snippet illustrates an example of @Component: The following code snippet illustrates an example of @Repository: @Component public class EmployeeService { @Autowired EmployeeDAO empDAO; @Override public String toString() { return empDAO; } } @Repository ("employeeDao") public class EmployeeDAO { public EmployeeDTO createNewEmployee() { EmployeeDTO e = new EmployeeDTO(); e.setId(1); e.setFirstName(“Jack"); e.setLastName(“Mathew"); return e; } }
  • 23. Slide 23 of 58© People Strategists www.peoplestrategists.com Spring provides validation support to validate the entered value. It provides a simplified set of APIs and supporting classes for validating domain objects. It also allows one to code the validation logic for custom validator. Introducing Spring Validation Framework The Spring MVC framework supports following validation implementation: Validator Custom Validator Bean Validation APi
  • 24. Slide 24 of 58© People Strategists www.peoplestrategists.com Spring provides the Validator interface to perform validation. The Validator interface can be used to validate an Object. It uses Error Object to report any validator error while validating an Object. The interface is available in the org.springframework.validation package. It has following two main methods: supports(Class):  Returns a boolean indicating whether or not the target class can be validated by this validator. validate(Object, org.springframework.validation.Errors):  In charge of actually performing validation. Introducing Spring Validation Framework (Contd.)
  • 25. Slide 25 of 58© People Strategists www.peoplestrategists.com The following code snippet shows implementation of the Validator interface: Introducing Spring Validation Framework (Contd.) public class PersonValidator implements Validator { /** * This Validator validates just Person instances */ public boolean supports(Class clazz) { return Person.class.equals(clazz); } public void validate(Object obj, Errors e) { ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); Person p = (Person) obj; if (p.getAge() < 0) { e.rejectValue("age", "negativevalue"); } else if (p.getAge() > 110) { e.rejectValue("age", "too. old"); } } }
  • 26. Slide 26 of 58© People Strategists www.peoplestrategists.com Spring provides the several annotations for data validation. It provides Bean Validation API to validate values of in a form tag. It has following validation annotation: @Size @NotEmpty @Email Introducing Spring Validation Framework (Contd.)
  • 27. Slide 27 of 58© People Strategists www.peoplestrategists.com The following code snippet declares the model class: Introducing Spring Validation Framework (Contd.) import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty @Email private String email; @NotEmpty(message = "Please enter your password.") @Size(min = 6, max = 15, message = "Your password must between 6 and 15 characters") private String password; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
  • 28. Slide 28 of 58© People Strategists www.peoplestrategists.com Activity: Implementing the Bean Validation API Let us see how to implement validation.
  • 29. Slide 29 of 58© People Strategists www.peoplestrategists.com Spring allows you to create custom validator. You can use Validator interface to implement custom validation. The following code snippet shows an example: Introducing Spring Validation Framework (Contd.) import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class StudentValidator implements Validator { public boolean supports(Class<?> clazz) { return Student.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "degree", "degree.required"); ValidationUtils.rejectIfEmpty(errors, "mark", "mark.required"); ValidationUtils.rejectIfEmpty(errors, "address", "address.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mail", "mail.required"); Student user = (Student) target; } }
  • 30. Slide 30 of 58© People Strategists www.peoplestrategists.com Activity: Implementing Custom Validation Let us see how to implement custom validation.
  • 31. Slide 31 of 58© People Strategists www.peoplestrategists.com The Data Access Object (DAO) support in Spring is aimed at making it easy to work with database technologies. It allows one to switch between the aforementioned persistence technologies fairly easily. It also allows one to code without worrying about catching exceptions that are specific to each technology. Introducing Spring DAO The Spring MVC framework makes use of the following components while processing a user request: JDBC Hibernate JPA JDO
  • 32. Slide 32 of 58© People Strategists www.peoplestrategists.com Identifying Advantages of Spring DAO Over JDBC Advanntage JDBC Spring Connections Need to explicitly open and close connections. Need a separate strategy for making code reusable in a variety of environments. Uses a DataSource with the framework managing connections. Code following the framework strategy is automatically reusable. Exceptions Must catch SQLExceptions and interpret database specific SQL error code or SQL state code. Framework translates exceptions to a common hierarchy based on configurable translation mappings. Testing Hard to test standalone if code uses JNDI lookup for connection pools. Can be tested standalone since a DataSource is easily configurable for a variety of environments Transaction Programmatic transaction management is possible but makes code less reusable in systems with varying transaction requirements. CMT is available for EJBs. Programmatic or declarativ e transaction management is possible. Declarative transaction management works with single data source or JTA without any code changes.
  • 33. Slide 33 of 58© People Strategists www.peoplestrategists.com Identifying Spring 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. Spring supports Java Persistence API (JPA). Spring JPA is a library / framework that adds an extra layer of abstraction on the top of our JPA provider. If you use Spring Data JPA, the repository layer of your application contains following three layers:
  • 34. Slide 34 of 58© People Strategists www.peoplestrategists.com Identifying Spring JPA (Contd.) Features of JPA POJO-based persistence model Support for enriched domain modeling Expanded query language Standardized object/relational mapping Usable in Java EE and Java SE environments Support for pluggable persistence providers Inheritance, polymorphism, etc. Using annotations and/or XML
  • 35. Slide 35 of 58© People Strategists www.peoplestrategists.com Identifying Spring JPA (Contd.) JPA Main Components Annotations Entity manager To label artifacts (classes, methods etc.) for persistence or persistence related operations A “gateway” to the persistence classes Allow access to persistent objects, transaction context, query language etc.
  • 36. Slide 36 of 58© People Strategists www.peoplestrategists.com Identifying Spring JPA (Contd.) Java Application Java Persistence API Hibernate TopLink Kodo (OpenJPA) Everyone can use their own favorite persistence technology Architecture of JPA.
  • 37. Slide 37 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA Download Hibernate Components Prepare Database, and Download JDBC Driver Implemented POJO entities and add annotations Persistence.xml Implemented client side code via EntityManager
  • 38. Slide 38 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Download Hibernate Components Prepare Database, and Download JDBC Driver 1. Hibernate Core 2. Hibernate EntityManager 3. Hibernate Annotations http://www.hibernate.org/ MySQL JDBC Driver http://tinyurl.com/ymt6rb
  • 39. Slide 39 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Implemented POJO entities and add annotations
  • 40. Slide 40 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.)
  • 41. Slide 41 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Configuring Persistence.xml Entity classes JDBC Driver JDBC URL User name password EntityManagerFactory Name
  • 42. Slide 42 of 58© People Strategists www.peoplestrategists.com Identifying Spring JPA (Contd.) JPA uses following annotations: @Entity: It signifies that a class is persistent and is attached to a class. @Id: It is an identity to of an entity class. It can be auto generated. @Column: It is put on getter of a class variable. It has functionalities such as, Updateable, Nullable, and Length . For example:
  • 43. Slide 43 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Entity Manager: It is a gateway to persistent classes It enables queries to retrieve records. It provides transaction facility outside the session beans.
  • 44. Slide 44 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Implemented client side code via EntityManager Persistence EntityManagerFactory EntityManagerDepartment Create Create Operates Persistence.xml
  • 45. Slide 45 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Creating Entity:
  • 46. Slide 46 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Finding an Entity:
  • 47. Slide 47 of 58© People Strategists www.peoplestrategists.com Implementing Spring JPA (Contd.) Updating an Entity:
  • 48. Slide 48 of 58© People Strategists www.peoplestrategists.com Integrating Spring with Hibernate The database layer is used to communicate with the relational database, and provides data persistence. To access data from a database, you need to implement a tool, such as Hibernate. Hibernate is a powerful Object Relation Mapping (ORM) tool that lies between the database layer and the business layer. It enables the application to access data from any database and provides data persistence. The Spring framework is placed between the application classes and the ORM tool. Spring enables you to use its features, such as DI and AOP, to configure objects in your application. Therefore, integration of Hibernate with Spring helps you use the Hibernate objects as Spring beans.
  • 49. Slide 49 of 58© People Strategists www.peoplestrategists.com Integrating Spring with Hibernate (Contd.) RDBMS Business Layer (Spring) Database Layer (Hibernate) Bean Management Declarative Transaction Management Hibernate Integration Service Beans Business Object Resource Management DAO Object Hibernate O/R Mapping Transaction Management
  • 50. Slide 50 of 58© People Strategists www.peoplestrategists.com Introducing ORM Most of the object-oriented applications use relational databases to store and manage the application data. The relational databases represent data in a tabular format, whereas data in object-oriented applications is encapsulated in a class. You can access a class by using its objects. However, to access the tabular data, you need to use a query language. Therefore, it is not possible to directly store the objects in a relational database. This difference between the object-oriented and relational database paradigms is called impedance mismatch. ORM is a process to map data representations in an object model having Java data types to a relational data model having SQL data type.
  • 51. Slide 51 of 58© People Strategists www.peoplestrategists.com Introducing ORM (Contd.) It is not possible to directly store the objects in a relational database. This difference between the object-oriented and relational database paradigms is called impedance mismatch. ORM is a process to map data representations in an object model having Java data types to a relational data model having SQL data type. Relational Databases Object-oriented applications Classes Tables Object
  • 52. Slide 52 of 58© People Strategists www.peoplestrategists.com Introducing ORM (Contd.) Configure the SessionFactory object in Spring Access and update data using Data Access Object To integrate Spring with Hibernate
  • 53. Slide 53 of 58© People Strategists www.peoplestrategists.com Introducing ORM (Contd.) Configuring the SessionFactory Object in Spring Create a Spring configuration file (spring-hibernate.xml) Declare a session factory by using the following code snippet: <bean id="mySessionFactory" class="org.springframework.orm.hiber nate4.LocalSessionFactoryBean"> <property name="configLocation" value="hibernate.cfg.xml"/> </bean>
  • 54. Slide 54 of 58© People Strategists www.peoplestrategists.com Introducing ORM (Contd.) Accessing and Updating Data Using DAO Create a DAO class and the sessionFactory object using DI Declare DAO as a bean in the configuration file Access DAO class’ methods, similar to other Spring beans
  • 55. Slide 55 of 58© People Strategists www.peoplestrategists.com Introducing ORM (Contd.) The following code snippet creates a DAO class: The following code snippet declares it as bean: The following code snippet accesses the methods of DAO class: The DAO class: ..................... public class CourseDetailsDAO { private SessionFactory sessionFactory; ..................... } <bean id="courseDetailsDao" class="university.CourseDetailsDAO"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> ApplicationContext apc=new ClassPathXmlApplicationContext("university/spring- hibernate.xml"); CourseDetailsDAO courseDao =(CourseDetailsDAO)apc.getBean("courseDetailsDao");
  • 56. Slide 56 of 58© People Strategists www.peoplestrategists.com Summary In this session, you learned that: You can implement autowiring by specifiying it in bean classes using the @Autowired annotation. With the @Autowired annotation you need to define the beans in the xml file so that the container is aware of them and can inject them for you. Spring provides Stereotype annotations, such as:  @Component  @Controller  @Repository  @Service @Component is a basic auto component scan annotation, it indicates annotated class is a auto scan component. @Repository is used to signify a persistence layer.
  • 57. Slide 57 of 58© People Strategists www.peoplestrategists.com Summary (Contd.) JPA is the sun specification for persisting objects in the enterprise application. It is currently used as the replacement for complex entity beans. If you use Spring Data JPA, the repository layer of your application contains following three layers:  Spring Data JPA  Spring Data Commons  JPA Provider The database layer is used to communicate with the relational database, and provides data persistence. To access data from a database, you need to implement a tool, such as Hibernate.
  • 58. Slide 58 of 58© People Strategists www.peoplestrategists.com Summary (Contd.) Hibernate is a powerful Object Relation Mapping (ORM) tool that lies between the database layer and the business layer. The Spring framework is placed between the application classes and the ORM tool. Spring enables you to use its features, such as DI and AOP, to configure objects in your application.