Spring Framework: Petr Kalina

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

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

z Spring is a framework extending the j2ee stack


z Addresses many of the common problems of this stack
z The "all or nothing" situation with the use of EJBs
z 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:

z class Seminar, needs some


instance of a class implementing Seminar
DiscussionModerator iface <<interface>>

z the problem is, how to locate the


DiscussionModerator
instance of such class

Bures Kalibera

Bulej
Example 1:

z pure Java (hardcoding):


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

z Spring:
ClassPathXmlApplicationContext appContext =
new ClassPathXmlApplicationContext(
new String[] { "seminar.xml" }
);

BeanFactory beanFactory = (BeanFactory) appContext;

Seminar seminar = new Seminar();


seminar.discussionModerator =
( DiscussionModerator) beanFactory.getBean("DiscussionModerator");

z seminar.xml:

<bean id="DiscussionModerator" class="example.Bulej"/>


Example 1:

z the difference:
– declarative definition of references
– instantiation left on Spring
z advantages
– swap in and out different implementations of objects at will
– create different configurations for different deployment scenarios
or for testing purposes
Discussion

z Dependency Injection
– the dependencies are "injected" to the program by the framework
and can be dealt with in a declarative way
z 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

z we want to use some kind of a Locator pattern:


z 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

z JNDI lookup with Locator – a "good" j2ee classics

client locator initialContext EJBHome EJBObject


get instance
of locator

create initial
context

lookup home lookup home


get service
object object

create EJB
get EJB object
object

complete perform
operation operation
Example 2: Locator pattern

Locator pattern in Spring:


z Asumptions:
– services are programmed to interfaces – can be EJBs, POJOs or
webservices..

CalculatorImplEJB

CalculatorClient CalculatorIface
CalculatorImplPOJO
Example 2: Locator pattern

z as an EJB
<bean id="CalculatorImpl" class="org.springframework.ejb.access.
LocalStatelessSessionProxyFactoryBean">
<property name="jndiName">
<value>calculatorBean</value>
</property>

<property name="businessInterface">
<value>exmaple.CalculatorIface</value>
</property>

</bean>

z Client code
BeanFactory bf = ( BeanFactory ) appContext;
CalculatorIface calculator = bf.getBean( "CalculatorImpl" );
Example 2: Locator pattern

z as a POJO
<bean id="calculatorImpl"
class="example.calculatorImplPOJO">
</bean>

z Client code ..is the same..


BeanFactory bf = (BeanFactory) appContext;
CalculatorIface calculator = bf.getBean("CalculatorImpl");
Example 2: Locator pattern

z Advantages:
– the same as Locator, but..
z the EJB nature of the CalculatorImpl service is hidden from the client
z the configuration can be changed declaratively
z we don't need to write Locator
z 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

z 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

z JDBC datasources..
z 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 student.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

z what's wrong there?


– nothing, it works, but...
– proliferate code
– datasource-nature (JNDI) specific code
– the SQLException
Example 3: datasources &
exceptions

z 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

z Spring templates...
class StudentsRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int index) throws SQLException {
Student student = new Student();
student.setFirstName( rs.getString( 1) );
student.setLastName( rs.getString( 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

z And where did the exceptions go?


– Templates map SQL exception into standard DAO exceptions
– DAO exceptions are Unchecked

DataAccessException

... ... DataIntegrityViolation InvalidDataAccessApiUsageException

... ... ... ...


Example 3: summary

z Discussion:
– swap JDBC datasources declaratively
– handle only the exceptions we want in database independent way
z Immediate impact on testing:
– swap JNDI for non-JNDI
Example 4:
Aspects
(flavor only..)
Example 4: aspects (flavor only..)

z 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..)

z AOP framework
– crosscutting aspects and concerns
– intercept method calls (accesses to members..) and perform
routines before or after this happens
– from outside the program
z no repetitious code
z the aspects and concerns are dealt with as aspects and concerns of
the whole application
Example 4: aspects (flavor only..)

z 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..)
Java class Spring bean
no caching..

serve*(*); DataAccessorIface

our buisiness object..


serve*(*){}; DataAccessorImpl "Implementation"

Object invoke(Params params) {


// decode params,
// try to get from cache
ServeMethodAdvice "AspectAction"
caching support..

// if not in cache, retrieve,


// add to cache and return
}

bean intercepting calls to mehods by regexp..


<property name="pattern">
<value>(serve).*</value> "Interceptor"
</property>

bean wiring up all "Weaver"


Example 4: aspects (flavor only..)

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

z Problems of classical transaction scenarios:


– Datasource vendor dependency and only local transactions
z when using local (ds specific) transactions
– Container lock-in, force of use of JNDI, non declarative approach
z when we controll transactions programatically with JTA (sun api for
transaction management relying on services of the j2ee container)
– Container and EJB lock-in
z when we decide to use the CMT (Container Managed Transactions),
which is a service of j2ee container for EJBs only

z Remember DB templates from ex. 3..


Example 5: Transactions (flavor..)

z Spring solves this problem in a classical way: by inserting a


level of absatraction
Spring beans..
hibernate_DS spring.hibernate_MGR internally a
single set of
JNDI_DS spring.JTA_MGR interfaces
accessed by
JDBC_DS spring.DS_MGR db templates

JdbcTemplate temp = new Jdbc(Hibernate, JDO)Template(ds);


temp.query( "update... )
...
Transactions (flavor..)

z Then Spring offers controll on various levels:


DB templates declarative
DS Utils

Transaction Templates programmatic

aspect oriented
approach to
transactions
Leftovers:
Leftovers (not even flavor..)

z Spring web and MVC


– Model-View-Controller perform requested manage user
pattern operations view/input

Model
View
(Business logic
(view utils)
and data storage)

Controller
call get commands
business call output
methods routines
summary:
What we've been through?

z We saw Spring in action in several of the


main areas

z 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

z Spring is based upon design patterns presented in a book by


Rod Johnson (Expert One-on-One J2EE Design and
Development, 2002)
z He is a member and a consultant of the Spring developer team
z 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

z against EJBs:
– testing implications – container lock-in
– heavyweight, steep learning curve
– hinder simple design
the EJBs

z 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

z EJBs are heavyweinght, make simple things hard (and hard


things simple..)
z many times misused causing bad development efficiency and
performance
Spring Role(s)

z POJO development with j2ee services


– transactions, AOP...
z Use of services is selective (not all Spring..)
z Advocate "good" design patterns
z Advocate IoC for better manageability

z Do we need EJBs at all?


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

z Discussion in Spring forums:


– "EJBs are "political" decission, no reasons to use them on technical
background"
z .. Spring extended by other frameworks (Tomcat , ActiveMQ)
– "the idea that Spring can be used as a generic application
server replacement is absurd"
z .. Spring applications deployed inside JBoss
– Conclusion??

• Good analysis 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

z and.. Thank you for your attention!

You might also like