Web Based Java All PPts Infoway
Web Based Java All PPts Infoway
By Rahul Barve
Introduction to JDBC
By Rahul Barve
Introduction to JDBC
JDBC stands for Java to Database Connectivity.
It is an API that allows Java applications to interact
with Database.
By Rahul Barve
Why JDBC
By Rahul Barve
Why JDBC
Applications need to write data into or load data from
database.
JDBC provides a channel to bridge the gap between a
Java application and a Database.
By Rahul Barve
Why JDBC
Java
JDBC Database
Application
By Rahul Barve
JDBC Driver
By Rahul Barve
JDBC Driver
Every DB vendor provides its own API that simplifies
access for the client programs to connecting to the
database.
Such an API is known as a Vendor Specific API.
By Rahul Barve
JDBC Driver
Since both the APIs are written as per the proprietary
standards, they are not compatible with each other.
This mismatch is resolved by a mediator known as a
Driver.
By Rahul Barve
JDBC Driver
Vendor
Java
JDBC Driver Specific Database
Application
API
By Rahul Barve
JDBC Driver
There are 4 types of JDBC drivers:
Type 1
Type 2
Type 3
Type 4
By Rahul Barve
Type 1 Driver
By Rahul Barve
Type 1 Driver
It is called as a JDBC – ODBC Bridge.
It uses a 3rd party library known as ODBC which is
provided by Microsoft.
By Rahul Barve
Type 1 Driver
Vendor
Java Type 1
JDBC ODBC Specific Database
Application Driver
API
By Rahul Barve
Type 1 Driver
It is platform dependent.
It is the slowest, takes much time for processing.
Every client machine must have ODBC configuration
setup.
By Rahul Barve
Type 1 Driver
Suitable for simple desktop applications or even just
for testing purpose.
Not much recommended in case of large scale
applications or even in production environment.
By Rahul Barve
Type 2 Driver
By Rahul Barve
Type 2 Driver
Native API, partly Java driver.
It uses a combination of Java as well as Database
proprietary standards for implementation.
By Rahul Barve
Type 2 Driver
Vendor
Java Type 2
JDBC Specific Database
Application Driver
API
By Rahul Barve
Type 2 Driver
It does not use any 3rd party library and hence it is
platform independent and faster in processing as
compared to Type 1.
By Rahul Barve
Type 2 Driver
Since it uses a DB specific native API, the
corresponding API must be installed on every client
machine.
By Rahul Barve
Type 3 Driver
By Rahul Barve
Type 3 Driver
Net Protocol, Intermediate DB Access Server
It is used especially when an application needs to
connect to multiple databases.
By Rahul Barve
Type 3 Driver
Vendor
Specific Database
API
Intermediate Vendor
Java Type 3 Specific
JDBC DB Access Database
Application Driver API
Server
Vendor
Specific Database
API
By Rahul Barve
Type 4 Driver
By Rahul Barve
Type 4 Driver
Database specific, Pure Java Driver.
Every DB vendor provides its own driver
implementation.
Directly connects to a DB server using TCP/IP socket
connections.
By Rahul Barve
Type 4 Driver
Vendor
Java Type 4
JDBC Specific Database
Application Driver
API
Socket with
IP Address and Port No
By Rahul Barve
Type 4 Driver
It is the fastest as compared to Type 1 and Type 2
drivers.
Platform independent.
By Rahul Barve
Type 4 Driver
No configuration is required on the client machine.
Hence, highly recommended for large scale
applications as well as production environment.
By Rahul Barve
JDBC Core API
By Rahul Barve
JDBC Core API
To implement any JDBC program, Java provides an
API known as a JDBC API.
It belongs to a package java.sql.
By Rahul Barve
JDBC Core API
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
By Rahul Barve
Steps in JDBC Application
By Rahul Barve
Steps in JDBC Application
Load the Driver.
Establish Connection.
Obtain the Statement.
Execute SQL query.
(For SELECT query) Obtain the ResultSet and
perform navigation.
By Rahul Barve
Load the Driver
By Rahul Barve
Load the Driver
A driver can be loaded either by using
Class.forName() or by creating an object of the
driver implementation class.
By Rahul Barve
Establish Connection
By Rahul Barve
Establish Connection
A Connection to the database can be established
either by using a DriverManager class or a
Driver interface.
By Rahul Barve
Establish Connection
E.g.
Connection conn =
DriverManager.getConnection(….);
OR
Driver dr =
new <<DriverImplClassNAME>>();
Connection conn = dr.connect(…);
By Rahul Barve
Obtain the Statement
By Rahul Barve
Obtain the Statement
Once a connection is established, depending upon the
type of the operation, a statement needs to be
obtained.
By Rahul Barve
Obtain the Statement
Statement is used to execute simple queries.
Statement stmt =
conn.createStatement();
By Rahul Barve
Execute SQL Query
By Rahul Barve
Execute SQL Query
Statement interface provides relevant methods to
execute SQL queries.
To execute SELECT query, executeQuery()
method is used that returns ResultSet.
By Rahul Barve
Execute SQL Query
String sqlQuery = “select ….”;
ResultSet rs =
stmt.executeQuery(sqlQuery);
By Rahul Barve
Perform Navigation
By Rahul Barve
Perform Navigation
ResultSet maintains data fetched from database in
a tabular format.
Every column has a column index and a row has a
record position.
By Rahul Barve
Perform Navigation
Before First 1 2 3
1
2
3
After Last
By Rahul Barve
Perform Navigation
By default, the cursor position of ResultSet points
to BeforeFirst.
To move in the forward direction, next() method is
used.
By Rahul Barve
Parameterized Queries
By Rahul Barve
Parameterized Queries
A query may accept parameters.
To execute parameterized queries,
PreparedStatement interface is used.
By Rahul Barve
Parameterized Queries
Queries created using PreparedStatement are
compiled once, hence are called as precompiled
queries.
By Rahul Barve
Parameterized Queries
E.g.
String sqlQuery =
“select … where deptno in (?, ?)”;
PreparedStatement pstmt =
conn.prepareStatement(sqlQuery);
By Rahul Barve
DML Queries
By Rahul Barve
DML Queries
To execute SELECT queries, executeQuery()
method is used whereas to execute DML queries,
executeUpdate() method is used.
By Rahul Barve
Transaction Management
By Rahul Barve
Transaction Management
Transaction Management is a very important activity
in an application development.
Transaction is a set of operations that must execute in
a single unit.
By Rahul Barve
Transaction Management
Updates made from Java application to database are
committed by default.
Once, changes are committed, cannot be rolled back.
By Rahul Barve
Transaction Management
To manage the transactions, auto-commit must be
disabled.
This is done by using setAutoCommit(false)
on the Connection object.
By Rahul Barve
Transaction Management
Once auto-commit is disabled, it is possible to commit
or rollback the transactions by using commit() or
rollback() methods respectively.
By Rahul Barve
Lets Summarize
What is JDBC
Why JDBC
JDBC Drivers
JDBC Core API
Executing Simple Queries
Executing Parameterized Queries
Transaction Management
By Rahul Barve
Revision no./Date:00/Oct.09 2008 By Rahul Barve 1
Objectives
HTTP Basics
Introduction to Servlets
Implementing Servlets
Life Cycle
Request Handling
GenericServlet
HttpServlet
ServletRequest ServletResponse
HttpServletRequest HttpServletReponse
pageContext.
setAttribute(“b”,“Welcome”,
pageContext.SESSION_SCOPE);
%>
%>
By Rahul Barve
Introduction to Hibernate
By Rahul Barve
Introduction to Hibernate
Hibernate is an Open Source Java Based Framework
that is used to build a Persistence Layer of an
application.
By Rahul Barve
Persistence Layer
By Rahul Barve
Introduction to Hibernate
Hibernate is a framework that is based upon some
principles known as ORM.
It is distributed into a single ZIP file which contains
several JAR files.
By Rahul Barve
Hibernate – Basic Architecture
By Rahul Barve
Hibernate – Basic Architecture
Application Classes
Hibernate
Database Server
By Rahul Barve
Hibernate – Core Architecture
By Rahul Barve
Hibernate – Core Architecture
By Rahul Barve
Hibernate – Core API
Configuration
Session
SessionFactory
Transaction
Query
By Rahul Barve
Configuration
By Rahul Barve
Configuration
org.hibernate.cfg.Configuration
Used to configure Hibernate based upon the
configurations through .properties or .xml
files or even programmatically.
By Rahul Barve
Session
By Rahul Barve
Session
org.hibernate.Session
An object representing a conversation between the
application and the persistent store.
Wraps a JDBC connection.
A client of TransactionFactory.
By Rahul Barve
Session
A Component used to persist or load objects to/from
the database.
Used to perform basic CRUD operations.
Provides utility methods like save(),
update(), delete(), load().
By Rahul Barve
SessionFactory
By Rahul Barve
SessionFactory
org.hibernate.SessionFactory
A factory for Session and a client of
ConnectionProvider.
By Rahul Barve
SessionFactory
Allows to instantiate Session
Heavyweight Component
Only one per application
By Rahul Barve
Transaction
By Rahul Barve
Transaction
org.hibernate.Transaction
An object used by the application to specify atomic
units of work.
By Rahul Barve
Transaction
Abstracts application from underlying JDBC or JTA
transaction.
Ensures that all the operations on persisted objects
occur in a transaction supported by either JDBC or
JTA.
Maintains Atomicity.
By Rahul Barve
ConnectionProvider
By Rahul Barve
ConnectionProvider
org.hibernate.connection.
ConnectionProvider
A factory for JDBC connections.
Abstracts application from underlying
Datasource or DriverManager.
By Rahul Barve
TransactionFactory
By Rahul Barve
TransactionFactory
org.hibernate.TransactionFactory
A factory for Transaction instances.
By Rahul Barve
Query
By Rahul Barve
Query
Used to perform Query operations across the
database.
Uses various clauses, functions to fine tune the
query results.
By Rahul Barve
Hibernate with Annotations
By Rahul Barve 1
Objectives
Introduction to Hibernate Annotations
Introduction to JPA
Working with Annotations
A Simple Example
By Rahul Barve 2
Hibernate Annotations
By Rahul Barve 3
Hibernate Annotations
Hibernate provides support for Mapping between
Class and Table, or Field and Column using
Annotations
By Rahul Barve 4
Hibernate Annotations
There are 2 ways to handle Annotation Based
mapping:
Using Hibernate Annotations
Using JPA Annotations
By Rahul Barve 5
What is JPA
By Rahul Barve 6
What is JPA
JPA stands for Java Persistence API.
A specification for managing entities in the
application domain.
By Rahul Barve 7
What is JPA
It is an abstraction on the top of any ORM framework
like Hibernate, Toplink, Eclipselink, Ibatis and so on.
By Rahul Barve 8
Why JPA
By Rahul Barve 9
Why JPA
Provides ease-of-use abstraction on top of JDBC.
Application code can be isolated from database,
vendor specific peculiarities and optimization.
By Rahul Barve 10
Why JPA
An Object-to-Relational Mapping (ORM) engine.
Provides a query language that is tailored to work
with java objects rather than relational schema.
By Rahul Barve 11
JPA Entities
By Rahul Barve 12
JPA Entities
JPA manages persistency with the help of simple
Java Entities.
JPA Entities are simple POJOs.
By Rahul Barve 13
Basic Annotations
By Rahul Barve 14
Basic Annotations
JPA provides 4 basic annotations:
@Entity
@Table
@Id
@Column
By Rahul Barve 15
@Entity
By Rahul Barve 16
@Entity
Tells the persistence provider about the entity class
which is being mapped to the database table.
Mandatory as far as annotation based metadata is
concerned.
By Rahul Barve 17
@Table
By Rahul Barve 18
@Table
Tells the EntityManager service about the
relational table to which the bean class maps.
If omitted, it defaults to the unqualified name of the
entity class.
By Rahul Barve 19
@Column
By Rahul Barve 20
@Column
Specifies the respective DB column to which the
entity class field maps.
Not required if class field name matches with the DB
column name.
By Rahul Barve 21
@Id
By Rahul Barve 22
@Id
Identifies one or more properties that make up the
primary key for the table.
Mandatory as far as annotation based metadata is
concerned.
By Rahul Barve 23
Let’s Summarize
Introduction to Hibernate Annotations
Introduction to JPA
Working with Annotations
A Simple Example
By Rahul Barve 24
By Rahul Barve
Objectives
Describe Hibernate Query Language (HQL)
Working with Queries
By Rahul Barve
Features
By Rahul Barve
Features
Used to execute queries against database.
Based on the relational object models.
By Rahul Barve
Features
Uses Classes and properties instead of tables and
columns.
Extremely powerful and it supports Polymorphism
and Associations.
By Rahul Barve
Features
The ability to apply restrictions to properties of
associated objects related by reference or held in
collections.
The ability to retrieve only properties of an entity or
entities, without the overhead of loading the entity.
By Rahul Barve
Features
The ability to order the results of the query.
The ability to paginate the results.
By Rahul Barve
Features
Provides support for aggregation with group by,
having, and aggregate functions like sum, min and
max.
Outer joins when retrieving multiple objects per row.
By Rahul Barve
Clauses
By Rahul Barve
Clauses
FROM
SELECT
WHERE
ORDER BY
By Rahul Barve
FROM
Used to load a set of entities from the underlying
database table.
The returned collection contains instances of an entity
class.
General Form: from Employee e
By Rahul Barve
SELECT
Used to retrieve selected fields from the underlying
database table.
The returned collection contains instances of array
type.
General Form: select e.name, e.sal from
Employee e
By Rahul Barve
Let’s Summarize
HQL
Querying using HQL
By Rahul Barve
By Rahul Barve 1
Objectives
What is Spring
Why Spring
Spring Features
Spring Modules
Spring Architecture
First Example
By Rahul Barve 2
What is Spring?
By Rahul Barve 3
What is Spring?
Spring is a lightweight dependency injection,
aspect-oriented container and framework.
By Rahul Barve 4
What is Spring?
Spring is a Container as it creates the Java
Components for your application and manages their
life-cycle.
By Rahul Barve 5
What is Spring Framework?
It is lightweight in terms of size and overhead.
It is distributed in a single ZIP file.
By Rahul Barve 6
Why Spring Framework?
By Rahul Barve 7
Why Spring Framework?
Java components running inside Spring container
have NO dependency on Spring specific Classes
and Interfaces.
By Rahul Barve 8
Why Spring Framework?
Spring enables to build applications from “plain old
Java objects” (POJOs) and to apply enterprise
services to POJOs
By Rahul Barve 9
Spring Features
By Rahul Barve 10
Spring Features
Loose Coupling
Dependency Injection
Aspect Oriented Programming
Data Access Support
Support for Enterprise Services
Integration Support
MVC Support
By Rahul Barve 11
Spring Features
Loose Coupling
Applications built using Spring are loosely coupled as it is
not required to modify the Java source code in order to
adopt changes in the configuration.
By Rahul Barve 12
Spring Features
Dependency Injection
A technique through which, the dependent objects are given to
the components so that components need not create dependent
objects themselves.
By Rahul Barve 13
Spring Features
Dependency Injection
public class Employee {
private Address addr;
//Some Code
}
By Rahul Barve 14
Spring Features
At the time of creating Employee, the container
injects the inner object (Address) inside the main
component (Employee).
By Rahul Barve 15
Spring Features
Dependency Injection
Dependency Injection (DI) is also known as Inversion Of
Control (IoC) as now the control is with the Container to
create the Dependent Object and inject it inside the
Component Object.
By Rahul Barve 16
Spring Features
Aspect Oriented Programming
AOP is a programming model that promotes separation
of business logic from the system concerns such as
logging, transaction management, security, persistence
etc.
By Rahul Barve 17
Spring Features
Aspect Oriented Programming
The code that implements these system wide concerns
is NOT duplicated across multiple components.
The component development is simple as they can
focus now only upon core business logic.
By Rahul Barve 18
Spring Features
Data Access Support
Spring abstracts away the common code like opening and
closing connections, so that the database code can be
clean and simple.
By Rahul Barve 19
Spring Features
Data Access Support
Spring doesn’t attempt to implement its own ORM
solution, but provides hooks into several popular ORM
frameworks like Hibernate, JPA, iBATIS etc.
By Rahul Barve 20
Spring Features
Support for Enterprise Services
An application built using Spring can acquire various
enterprise level services like:
Transaction Management
Persistence
Asynchronous Messaging
Security
Task Scheduling
By Rahul Barve 21
Spring Features
Integration Support
Spring provides support for integration with other
technologies like EJB, JNDI, Web Services etc.
Already implemented services can be consumed very
efficiently using Spring.
By Rahul Barve 22
Spring Features
MVC Support
Spring comes with its own MVC framework and even it
can integrated with existing popular MVC frameworks
like Struts, JSF, Tapestry etc.
By Rahul Barve 23
ApplicationContext
Built on the top of core container.
Provides support for internationalization,
application life cycle events and validation.
By Rahul Barve 24
Spring Framework – Core Modules
By Rahul Barve 25
Let’s Summarize
What is Spring
Why Spring
Spring Features
Spring Modules
Spring Architecture
First Example
By Rahul Barve 26
By Rahul Barve 1
Objectives
Introduction to Spring’s Annotation Support
Bean Configuration
Using Various Annotations
By Rahul Barve 2
Spring Annotations
By Rahul Barve 3
Spring Annotations
Spring Framework provides support for Annotation
Based Metadata to handle RAD.
Developers may discard XML totally and take full
advantage of Spring Annotations.
By Rahul Barve 4
Spring Annotations
In Annotation based configuration, there are further
2 options:
Java Based Configuration
Pure Annotation Based Configuration
By Rahul Barve 5
Configuring Beans
By Rahul Barve 6
Configuring Beans
To configure beans, Spring provides 2 basic
annotations:
@Configuration
@Bean
By Rahul Barve 7
@Configuration
By Rahul Barve 8
@Configuration
Applied at the class level to introduce a class as a
Configuration Unit.
Classes annotated with @Configuration act as
entry points of the spring configuration unit.
By Rahul Barve 9
@Bean
By Rahul Barve 10
@Bean
Applied at the method level to indicate that a
method is a Bean Creation Method.
Objects returned by methods annotated with @Bean
are treated as managed components in the Spring
Environment.
By Rahul Barve 11
Retrieving Beans
By Rahul Barve 12
Retrieving Beans
Beans registered in the annotation based
configuration unit are obtained using a class
AnnotationConfigApplicationContext.
By Rahul Barve 13
AnnotationConfigApplicationContext
By Rahul Barve 14
AnnotationConfigApplicationContext
By Rahul Barve 15
Components
By Rahul Barve 16
Components
@Bean annotation can be used to configure beans in
the configuration unit.
However, developer needs to create these objects
explicitly.
By Rahul Barve 17
Components
To enable Spring to create Java Objects using
Reflection API, Spring provides a stereotype
annotation @Component.
By Rahul Barve 18
Components
@Component
Applied at the class level to mark that class as a
Component class.
By Rahul Barve 19
Scanning Components
By Rahul Barve 20
Scanning Components
Once a component is declared, it is to be scanned in
the configuration unit and that is accomplished by an
annotation @ComponentScan.
By Rahul Barve 21
Let’s Summarize
Spring’s Annotation Support
Bean Configuration
Component Scanning
Using Various Annotations
By Rahul Barve 22
By Rahul Barve 1
Objectives
Understand Aspect Oriented Programming.
Why AOP
AOP Terminologies
Weaving
Implementing AOP
By Rahul Barve 2
What is AOP
By Rahul Barve 3
What is AOP
AOP is a programming model that promotes
separation of business logic from cross-cutting
concerns.
By Rahul Barve 4
What is AOP
A cross-cutting concern can be described as any
functionality that affects multiple points of an
application.
By Rahul Barve 5
What is AOP
These cross-cutting concerns can be modularized into
special objects called Aspects.
By Rahul Barve 6
AOP – Big Picture
By Rahul Barve 7
Benifits
Aspects offer an alternative to inheritance and
delegation that can be cleaner in many circumstances.
Secondary concerns are decoupled from primary
concerns.
Allows developers to focus upon business logic.
By Rahul Barve 8
AOP Terminology
By Rahul Barve 9
AOP Terminology
There are 5 terms involved in Spring AOP:
Advice
Joinpoint
Pointcut
Aspect
Weaving
By Rahul Barve 10
AOP Terminology
Advice
Aspects have a purpose, a job they are meant to do.
The job of an aspect is called advice.
It defines both: WHAT and WHEN of an aspect.
By Rahul Barve 11
AOP Terminology
JoinPoint
A joinpoint is a point in the execution of the application
where an aspect can be plugged in.
By Rahul Barve 12
AOP Terminology
Pointcut
If advice defines WHAT and WHEN of an aspect, then
pointcut defines WHERE.
A pointcut definition matches one or more joinpoints at
which advice should be woven.
By Rahul Barve 13
AOP Terminology
Aspect
An aspect is the merger of advice and pointcut.
It specifies what to do, when to do and where to do.
By Rahul Barve 14
Weaving
Weaving is the process of applying aspects to a
target object to create a new, proxied object.
The aspects are woven into the target object at the
specified join points.
By Rahul Barve 15
Weaving
Weaving can take place at three different points:
Compile time
Classload time
Runtime
By Rahul Barve 16
Weaving
Compile time
Aspects are woven in when the target class is compiled.
By Rahul Barve 17
Weaving
Classload Time
Aspects are woven in when the target class is loaded into
the JVM.
This requires a special class loader that enhances the byte
code before the class is introduced to the application.
By Rahul Barve 18
Weaving
Runtime
Aspects are woven in sometime during the execution of the
application.
Typically, an AOP container will dynamically generate a
proxy object that will delegate to the target object while
weaving in the aspects.
This is how Spring AOP aspects are woven.
By Rahul Barve 19
Spring AOP support
By Rahul Barve 20
Spring AOP support
Spring Advices are written in Java.
Spring applies an Advice to an Object at runtime, by
wrapping them with a proxy class.
By Rahul Barve 21
Spring AOP support
Between the time that the proxy intercepts the
method call and the time it invokes the target bean’s
method, the proxy performs the aspect logic.
Spring only supports method joinpoints.
By Rahul Barve 22
Types of Spring AOP Advices
By Rahul Barve 23
Types of Spring AOP Advices
Before Advice
After returning Advice
After throwing Advice
After Advice
Around Advice
By Rahul Barve 24
Before Advice
Causes a method to be invoked before the invocation
of a target method.
By Rahul Barve 25
After Returning Advice
Causes a method to be invoked after successful
invocation of a target method.
By Rahul Barve 26
After Throwing Advice
Causes a method to be invoked if an exception is
occurred during an execution of the target method.
By Rahul Barve 27
After Advice
Causes a method to be invoked irrespective of
whether a target method completes successfully or
not.
By Rahul Barve 28
Around Advice
A single advice that wraps up all types of advices.
Provides a single method through which other advice
methods are invoked.
By Rahul Barve 29
Enabling Proxying
By Rahul Barve 30
Enabling Proxying
Since in AOP, spring performs weaving with the help
of proxies, it’s necessary to enable Proxy in the
application.
By Rahul Barve 31
Enabling Proxying
To enable proxy, the configuration specific class must
be annotated with @EnableAspectJAutoProxy.
By Rahul Barve 32
Spring’s AOP Annotations
By Rahul Barve 33
Spring’s AOP Annotations
Spring comes with Annotation Based Support,
through AspectJ annotations for AOP.
By Rahul Barve 34
Spring’s AOP Annotations
AOP Annotations:
@Aspect
@Before
@AfterReturning
@AfterThrowing
@After
@Pointcut
@Around
By Rahul Barve 35
@Aspect
Applied at the class level.
Tells Spring that the class is not just a POJO, rather
it’s an aspect.
Classes annotated with @Aspect will only be
considered as Aspects.
By Rahul Barve 36
@Before
Applied at the method level.
Annotated methods will be called before the
execution of advised method.
By Rahul Barve 37
@AfterReturning
Applied at the method level.
Annotated methods will be called after the
successful return of the advised method.
By Rahul Barve 38
@AfterThrowing
Applied at the method level.
Annotated methods will be called if some exception
is raised during the execution of the advised
method.
By Rahul Barve 39
@After
Applied at the method level.
Annotated methods will be called after the
execution of the advised method, irrespective of
whether the advised method returns successfully or
not.
By Rahul Barve 40
@Pointcut
Used to define a pointcut.
Applied at the method level to mark the method as a
pointcut.
The marked method can be used for further
referencing.
By Rahul Barve 41
@Around
Applied at the method level to mark the method as a
an Around Advice.
Uses a Pointcut expression to apply the aspect.
By Rahul Barve 42
Let’s Summarize
What is AOP
Why AOP
AOP Terminologies
Types of Advices
Weaving
Implementing AOP
By Rahul Barve 43
By Rahul Barve 1
Objectives
Working with ApplicationContext
Bean Life Cycle
Understanding Dependency Injections
Bean Scopes
Auto-wiring
By Rahul Barve 2
ApplicationContext
In a Spring-based application, the application objects live
within the Spring Container.
The container creates the objects, wire them together,
configure them, and manage their lifecycle.
By Rahul Barve 3
ApplicationContext
The ApplicationContext interface standardizes the Spring
bean container behavior.
Its implementations form the simple container, providing
basic support for DI.
Supports I18N.
Supports Event Management.
By Rahul Barve 4
ApplicationContext
Spring comes with several flavors of
ApplicationContext.
FileSystemXmlApplicationContext
ClassPathXmlApplicationContext
XmlWebApplicationContext
By Rahul Barve 5
FileSystemXmlApplicationContext
Loads a context definition from an XML file located
in the file system.
E.g.
ApplicationContext ctx;
String file = “c:/config.xml”;
ctx =
new
FileSystemXmlApplicationContext(file);
By Rahul Barve 6
ClassPathXmlApplicationContext
Loads a context definition from an XML file located
in the classpath.
E.g.
ApplicationContext ctx;
String file = “config.xml”;
ctx =
new ClassPathXmlApplicationContext(file);
By Rahul Barve 7
XmlWebApplicationContext
Loads a context definition from an XML file
contained within a web application.
Used in Spring MVC environment.
By Rahul Barve 8
Bean Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="emp"
class="com.emp.Employee">
</bean>
</beans>
By Rahul Barve 9
Bean Configuration File
bean: The Element which is the most basic
configuration unit in Spring. It tells Spring Container to
create an Object.
id: The Attribute which gives the bean a unique name by
which it can be accessed.
class: The Attribute which tells Spring the type of a
Bean.
By Rahul Barve 10
Accessing Bean
ApplicationContext ctx;
String file = “c:/config.xml”;
ctx = new
FileSystemXmlApplicationContext(file);
GreetingService service;
service =
(GreetingService)ctx.getBean(“greet”);
By Rahul Barve 11
How DI/IoC Container works
In Inversion Of Control (IoC), control is inverted back
to the Container to support the object dependencies.
IoC container creates the POJO objects and provides
dependencies to them.
These POJO objects are not tied to any framework.
The declarative configuration for POJO objects is
defined with unique identities (id) in XML.
These are known as bean definitions.
By Rahul Barve 12
How DI/IoC Container works
The IoC container at runtime identifies POJO bean
definitions, creates bean objects and returns them to
the Application.
IoC container manages dependencies of the objects.
By Rahul Barve 13
Injecting the Dependencies
The IoC container will Inject the dependencies in
three ways
Create the POJO objects by using no-argument
constructor and injecting the dependent
properties by calling the setter methods.
By Rahul Barve 14
Injecting the Dependencies
The IoC container will Inject the dependencies in
three ways
Create the POJO objects by using no-argument
constructor and injecting the dependent
properties by calling the setter methods.
Create the POJO objects by using
parameterized constructors and injecting the
dependent properties through the constructor.
By Rahul Barve 15
Injecting the Dependencies
The IoC container will Inject the dependencies in
three ways
Create the POJO objects by using no-argument
constructor and injecting the dependent
properties by calling the setter methods.
Create the POJO objects by using
parameterized constructors and injecting the
dependent properties through the constructor.
Implements the method Injection.
By Rahul Barve 16
Injecting Properties by calling Setters
public Class Employee {
private String fname, lname;
public Employee(){}
By Rahul Barve 17
Injecting Properties by calling Setters
<bean id="emp"
class="com.emp.Employee">
<property name=“fname” value=“a”/>
<property name=“lname” value=“b”/>
</bean>
By Rahul Barve 18
Bean LifeCycle
By Rahul Barve 19
Bean LifeCycle
Instantiate Populate BeanNameAware's
Properties setBeanName()
BeanFactoryAware's ApplicationContextAware's
setBeanFactory() setApplicationContext()
By Rahul Barve 20
Bean Life Cycle
Instantiate: Spring instantiates the bean.
Populate properties: Spring injects the bean’s
properties.
Set bean name: If the bean implements
BeanNameAware, Spring passes the bean’s ID
to setBeanName().
By Rahul Barve 21
Bean Life Cycle
Set Application Context: If the bean implements
ApplicationContextAware, Spring passes
the application context to
setApplicationContext().
Postprocessor (before initialization): If there are
any BeanPostProcessors, Spring calls their
postProcessBeforeInitialization()
method.
By Rahul Barve 22
Bean Life Cycle
Initialize beans: If the bean implements
InitializingBean, its
afterPropertiesSet() method will be called.
If the bean has a custom init method declared, the
specified initialization method will be called.
Postprocessor (after initialization): If there are any
BeanPostProcessors, Spring calls their
postProcessAfterInitialization()
method.
By Rahul Barve 23
Bean Life Cycle
Bean is ready to use. At this point the bean is ready
to be used by the application and will remain in the
bean factory until it is no longer needed.
Destroy bean: If the bean implements
DisposableBean, its destroy() method will
be called. If the bean has a custom destroy-method
declared, the specified method will be called.
By Rahul Barve 24
Injecting Properties through Constructors
public Class Employee {
private String fname, lname;
public Employee(String f,String l ){
fname = f;
lname = l;
}
}
By Rahul Barve 25
Injecting Properties through Constructors
<bean id="emp"
class="com.emp.Employee">
<constructor-arg value=“Joe"/>
<constructor-arg value=“Thomas"/>
</bean>
By Rahul Barve 26
Dependent Beans
By Rahul Barve 27
Dependent Beans
A bean is a dependency of another bean, is
expressed by the fact that, one bean is set as a
property of another.
By Rahul Barve 28
Dependent Beans
It is achieved with the <ref/> element or ref
attribute in XML based configuration metadata of
beans.
By Rahul Barve 29
Bean Loading
By Rahul Barve 30
Bean Loading
In Spring, Bean Loading happens by 2 ways:
EAGER (DEFAULT)
LAZY
By Rahul Barve 31
Bean Loading
The bean registered in the configuration unit gets
instantiated as soon as the ApplicationContext
is built.
This is known as EAGER Loading.
By Rahul Barve 32
Bean Loading
The bean registered in the configuration unit gets
instantiated only when the client program makes a
request for the same.
This is known as LAZY Loading.
By Rahul Barve 33
AutoWiring
By Rahul Barve 34
AutoWiring
Rather than explicitly wiring all of your bean’s
properties, you can have Spring automatically figure
out how to wire beans.
It is done by setting the autowire property.
By Rahul Barve 35
AutoWiring
Spring provides 3 types of autowiring:
byName
byType
constructor
By Rahul Barve 36
AutoWiring
byName
Attempts to find a bean in the container whose
name is the same as the name of the property
being wired.
By Rahul Barve 37
AutoWiring
byType
Attempts to find a single bean in the container
whose type matches the type of the property being
wired.
By Rahul Barve 38
AutoWiring
constructor
Tries to match up a constructor of the autowired bean
with beans whose types are assignable to the
constructor arguments.
By Rahul Barve 39
Bean Scopes
By Rahul Barve 40
Bean Scopes
Every bean registered in XML file has some scope.
It is possible to modify scope of the bean using
scope attribute of <bean> element.
By Rahul Barve 41
Bean Scopes
There are 5 different types of scopes:
singleton
prototype
request
session
global-session
By Rahul Barve 42
Bean Scopes
singleton
It is the default scope.
Indicates that the bean configuration is singleton.
If the same bean is requested multiple times, spring
returns the same object.
By Rahul Barve 43
Bean Scopes
prototype
Antonym of singleton.
If the same bean is requested multiple times, spring
returns the a new object every time.
By Rahul Barve 44
Bean Scopes
request
Applicable only in the context of Spring MVC.
The bean is alive until the response is generated.
For every new instance of HttpServletRequest, spring
creates a new instance.
By Rahul Barve 45
Bean Scopes
session
Applicable only in the context of Spring MVC.
The bean is alive until the session is over.
Bean can survive even if the response is generated.
For every new instance of HttpSession, spring creates a
new instance.
By Rahul Barve 46
Bean Scopes
global-session
Applicable in the context of Spring Portlet environment.
The bean is alive across multiple portlets.
By Rahul Barve 47
Let’s Summarize
Working with ApplicationContext
Bean Life Cycle
Understanding Dependency Injections
Auto-wiring
Bean Scopes
By Rahul Barve 48