spring framework - iii
TRANSCRIPT
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.AutowiredAnnotationBeanPostProcessor"/>
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 controllercomponent. 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:
ValidatorCustom
ValidatorBean 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.validationpackage.
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 Validatorinterface:
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
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
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 implementvalidation.
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 followingthe framework strategy isautomatically 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 etransaction management is possible. Declarative transaction managementworks 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
AnnotationsEntity
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.xmlImplemented
client side code via EntityManager
Slide 38 of 58© People Strategists www.peoplestrategists.com
Implementing Spring JPA (Contd.)
Download HibernateComponents
Prepare Database, and Download JDBC Driver
1. Hibernate Core2. Hibernate EntityManager3. Hibernate Annotationshttp://www.hibernate.org/
MySQL JDBC Driverhttp://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.