Spring framework

materialisticrampantInternet and Web Development

Nov 10, 2013 (4 years ago)

83 views

Spring framework
Petr
Kalina
This Presentation
1.
The minimal basics
2.
Spring in action –
5 examples
3.
Spring role in j2ee
world discussion
Minimal Basics

Spring is a framework extending the j2ee
stack

Addr
esses
many of the common problems of this stack

The "all or nothing" situation with the use of EJBs

Spring makes EJBs
optional and services selective
This Presentation
1.
The minimal basics
2.
Spring in action –
5 examples
3.
Spring role in j2ee
world discussion
Example 1:
Absolute Basics
-Inversion of Control
-Dependency Injection
Example 1:

class Seminar, needs some
instance of a class implementing
DiscussionModerator
iface

the problem is, how to locate the
instance of such class
Seminar
<<interface>>
Bures
DiscussionModerator
Kalibera
Bulej
Example 1:

pure Java (hardcoding):
Seminar seminar
= new Seminar();
seminar.discussionModerator
= new Bulej();
Example 1:

Spring:
ClassPathXmlApplicationContext
appContext
=
new
ClassPathXmlApplicationContext(
new
String[] { "seminar.xml" }
);
BeanFactory
beanFactory
= (BeanFactory) appContext;
Seminar seminar
= new Seminar();
seminar.discussionModerator
=
(
DiscussionModerator) beanFactory.getBean("DiscussionModerator");
<bean
id="DiscussionModerator" class="example.Bulej"/>

seminar.xml:
Example 1:

the difference:

declarative definition of references

instantiation left on Spring

advantages

swap in and out different implementations of objects at will

create different configurations for different deployment scenarios
or for testing purposes
Discussion

Dependency Injection

the dependencies are "injected" to the program by the framework
and can be dealt with in a declarative way

Inversion of Control

the program is not in control of the framework, but to the contrary,
the framework controls the program
Example 2:
The JNDI steps in..
Example 2: motivation

we want to use some kind of a Locator pattern:

the idea of a Locator:

multiple tiers

client/service needs to locate collaborator

no lookups in the client/business code, all wrapped in single class,
a Locator
Example 2: Locator pattern

JNDI
lookup with Locator –
a "good" j2ee
classics
client
locator
initialContext
EJBHome
EJBObject
get instance
of locator
get service
create initial
context
lookup home
object
lookup home
object
create EJB
object
get EJB object
perform
operation
complete
operation
Example 2: Locator pattern
Locator pattern in Spring:

Asumptions:

services are programmed to interfaces

can be EJBs, POJOs
or
webservices..
CalculatorClient
CalculatorIface
CalculatorImplEJB
CalculatorImplPOJO
Example 2: Locator pattern

as an EJB
<bean
id="CalculatorImpl" class="org.springframework.ejb.access.
LocalStatelessSessionProxyFactoryBean">
<property
name="jndiName">
<value>calculatorBean</value>
</property>
<property
name="businessInterface">
<value>exmaple.Calcu
latorIface</value>
</property>
</bean>
BeanFactory
bf
= (
BeanFactory
) appContext;
CalculatorIface
calculator
= bf.getBean(
"CalculatorImpl"
);

Client code
Example 2: Locator pattern

as a POJO
<bean
id="calculatorImpl"
class="example.calculatorImplPOJO">
</bean>
BeanFactory
bf
= (BeanFactory) appContext;
CalculatorIface
calculator
= bf.getBean("CalculatorImpl");

Client code ..is the same..
Example 2: Locator pattern

Advantages:

the same as Locator, but..

the EJB nature of the CalculatorImpl
service is hidden from the client

the configuration can be changed declaratively

we don't need to write Locator

Immediate impact on testing:

we can easily swap EJB objects for stubbed objects for Unit
Testing .. (stubbed = POJO returning already stub-wrapped
responses –
don't depend on container at all)
Example 2: Locator pattern

Alert

Spring dependency in client !!!

... isn't necessary, we can inject the dependencies from the
application context
<bean id="adderImpl" ..
<bean id="multiplierImpl" ..
<bean
id="calculatorImpl"
class="example.calculatorImplPOJO">
<ref bean="adderImpl" />
<ref bean="multiplierImpl" />
...
</bean>
Example 3:
Datasources
&
Exceptions
Example 3: motivation

JDBC datasources..

Imagine a classical database handling block in JDBC:
Example 3: motivation
Connection
con
= null;
try
{
javax.sql.Datasource
ds
=
(javax.sql.Datasource) ctx.Lookup("myDataSource");
con
= ds.getConnection();
Statement
stmt
= con.createStatement();
String
query
= "SELECT
NAME,SURENAME
FROM
SEMINARSTUDENTS";
ResultSet
rs
= stmt.executeQuery(
query
);
while
(
rs.next()
) {
String
s
tudent.name
= rs.getString("NAME");
String student.surename
= rs.getString("SURENAME");
studentlist.add( student );
}
}
catch
(SQLException
ex){

logger.error("SQL ERROR!",ex);
}
finally
{ con.close();
}
Example 3: more motivation

what's wrong there?

nothing, it works, but...

proliferate code

datasource-nature (JNDI) specific code

the SQLException
Example 3: datasources
&
exceptions

Spring datasources
accessed as beans..
<bean
id="myDataSourceJNDI"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property
name="jndiName">
<value>java:comp/env
/jdbc/myds</value>
</property>
</bean>
<bean
id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property
name="driverClassName">
<value>org.gjt.mm.mysql.Driver</value></property>
<property
name="url">
<value>jdbc:mysql://seminar/students</value></property>
<property
name="username">
<value>petr</value></property>
<property
name="password">
<value>password</value></property>
</bean>
Example 3: datasources
&
exceptions

Spring templates...
class
StudentsRowMapper
implements
RowMapper
{
public Object
mapRow(ResultSet
rs, int
index) throws
SQLException
{
Student student
= new
Student();
student.setFirstName
(
rs.getString(
1)
);
s
t
u
d
e
n
t
.
s
e
t
L
a
s
t
N
a
m
e
(r
s
.
g
e
t
S
t
r
i
n
g
(2))
;
return
student;
}
DataSource
ds
= (DataSource) bf.getBean("myDataSource");
JdbcTemplate
temp = new
JdbcTemplate(ds);
List studentList =
temp.query(
"select
student.name
FROM
students",
new StudentsRowMapper() );
Example 3: datasources
&
exceptions

And where did the exceptions go?

Templates map SQL exception into standard DAO exceptions

DAO exceptions are Unchecked
DataAccessException
DataIntegrityViolation
InvalidDataAccessApiUsageException
...
...
...
...
...
...
Example 3: summary

Discussion:

swap JDBC datasources
declaratively

handle only the exceptions we want in database independent way

Immediate impact on testing:

swap JNDI for non-JNDI
Example 4:
Aspects
(flavor only..)
Example 4: aspects (flavor only..)

Imagine a typical business object in enterprise environment:
Example 4: aspects (flavor only..)
public class
MyBusinessClass
extends
OtherBusinessClass
{
// Core
data members
// Other
data members: Log stream, data-consistency
flag
// Override
methods
in the
base class
public void
performSomeOperation(OperationInformation
info) {
// Ensure
authentication
// Ensure
info
satisfies
contracts
// Lock
the
object
to ensure
data-consistency
// Ensure
the
cache
is
up
to date
// Log the
start of
operation
// ==== Perform
the
core
operation
====
// Log the
completion
of
operation
// Unlock
the
object
}
public void
save(PersitanceStorage
ps) {}
public void
load(PersitanceStorage
ps) {}
}
Example 4: aspects (flavor only..)

AOP framework

crosscutting aspects
and concerns

intercept method calls (accesses to members..) and perform
routines before or after this happens

from outside the program

no repetitious code

the aspects
and concerns
are dealt with as aspects and concerns of
the whole application
Example 4: aspects (flavor only..)

the flavor:

application accesses data on remote datasource
and serves them
to the client on request.

we write the application without caching, then we want to change
this aspect and we want to have all once served data cached

the business methods:
serveDataById( int
id );
serveDataByName( string name );
serveDataBy...
Example 4: aspects (flavor only..)
DataAccessorIface
DataAccessorImpl
"Implementation"
Java class
Spring bean
our buisiness
object..
ServeMethodAdvice
serve*(*){};
serve*(*);
Object invoke(Params
params) {
// decode params,
// try to get from cache
// if not in cache, retrieve,
// add to cache and return
}
"AspectAction"
"Weaver"
bean wiring up all
"Interceptor"
bean intercepting calls to mehods
by regexp..
<property
name="pattern">
<value>(serve).*</value>
</property>
no caching..
caching support..
Example 4: aspects (flavor only..)

Observation:

there's an AOP framework in Spring
Example 5:
Transactions
(flavor only..)
Transactions (flavor..)

Problems of
classical transaction scenarios:

Datasource
vendor dependency and only local transactions

when using local (ds
s
pecific) transactions

Container lock-in, force of use of JNDI, non declarative approach

when we controll
transactions programatically
with JTA (sun api
for
transaction management relying on se
rvices of the j2ee container)

Container and EJB lock-in

when we decide to use the CMT (Container Managed Transactions),
which is a service of j2ee container for EJBs
only

Remember DB templates from ex. 3..
Example 5: Transactions (flavor..)

Spring solves this problem in a classical way: by inserting a
level of absatraction
hibernate_DS
JNDI_DS
JDBC_DS
spring.hibernate_MGR
spring.JTA_MGR
spring.DS_MGR
internally a
single set of
interfaces
accessed by
db templates
JdbcTemplate
temp = new
Jdbc(Hibernate, JDO)Template(ds);
temp.query(
"update... )
...
Spring beans..
Transactions (flavor..)

Then Spring offers controll
on various levels:
declarative
DB templates
DS Utils
Transaction Templates
programmatic
aspect oriented
approach to
transactions
Leftovers:
Leftovers (not even flavor..)

Spring web and MVC

Model-View-Controller
pattern
perform requested
operations
manage user
view/input
View
(view utils)
Model
(Business logic
and data storage)
Controller
get commands
call output
routines
call
business
methods
summary:
What we've been through?

We saw Spring in action in several of the
main areas

Now we're ready for discussion of it's role in
the "J2EE world"
This Presentation
1.
The minimal basics
2.
Spring in action –
5 examples
3.
Spring role in j2ee world discussion
j2ee & Spring

Spring is based upon design patterns presented in a book by
Rod Johnson (Expert One-on-One
J2EE
Design and
Development
,
2002)

He is a member and a consultant of the Spring developer team

My understanding of the abstract of the book:

j2ee is generally a good thing, only one has to be very selective
about what parts he really needs

the j2ee bundle does not enforce or even advocate a good design
strategy on developer and thus is vary often misused

respecting some design patterns leads to lower-cost / higher
performance, reusability, testability applications

the EJBs
are overused in j2ee common practice
the EJBs

against EJBs:

testing implications –
container lock-in

heavyweight, steep learning curve

hinder simple design
the EJBs

for EJBs:

scalability (clustering, distribution)

distribution (stateless session EJBs)

message driven scenarios (MDBs)

no need to write complex multithreaded code

transparent global transaction management in the container

security services in the container

EJBs
are more or less familiar to everyone

DB vendor independence
EJB -
Observation

EJBs
are heavyweinght, make simple things hard (and hard
things simple..)

many times misused causing bad development efficiency and
performance
Spring Role(s)

POJO development with j2ee services

transactions, AOP...

Use of services is selective (not all Spring..)

Advocate "good" design patterns

Advocate IoC
for better manageability

Do we need EJBs
at all?

Is Springs role to replace the EJB containers?
Jboss
vs. Spring

Discussion in Spring forums:

"EJBs
are "political" decission, no reasons to use them on technical
background"

.. Spring extended by other frameworks (Tomcat , ActiveMQ)

"the
idea that
Spring
can
be
used
as a generic
application
server replacement
is
absurd"

.. Spring applications deployed inside JBoss

Conclusion??

Good analys
is and case-by-case approach is the key!!

If we really need full featured container, it's JBoss
or like..

For the rest (a very big part..) it's the Spring
Questions

and.. Thank you for your attention!