Enterprise Service Abstractions
SPRING FRAMEWORK
July 27, 2008
1
Spring Framework
Agenda
Evolution
Data Access
JDBC
ORM (Hibernate)
Transaction Management
Integration
Remoting & Web Services
EJB
JMS
JMX
Email
Scheduling
Thread Pooling
Dynamic Language Support
References
Questions/Feedback
July 27, 2008
2
Spring Framework
01 Evolution
July 27, 2008
3
Spring Framework
Compatibility
Spring 2.0 compatible with Java 1.4.2, Java 5 and Java 6
Spring 2.5 has dedicated support for Java 6
Spring 2.0 compatible with J2EE 1.3 and higher
BEA Weblogic 8.1, 9.0, 9.1, and 10
IBM Websphere 5.1, 6.0 and 6.1
Oracle OC4J 10.1.3 and 11
JBoss 3.2, 4.0 and 4.2
Tomcat 4.1, 5.0, 5.5, and 6.0
Jetty 4.2, 5.1, and 6.1
Resin 2.1, 3.0, and 3.1
Glassfish V1 and V2
July 27, 2008
4
Spring Framework
Journey
Inversion of Control Container
Bean scopes
Has pre-built 5 scopes, support for custom scopes
Easier XML Authoring via Namespaces and complete tag-based configuration
Add you own tags via Extensible XML authoring support
Support for Annotations
Spring 2.5 has extensive annotation support alongwith JSR-250 annotations
Ability to auto-detect components in classpath (via annotations)
AOP
Support for @AspectJ aspect declaration annotations
Uses generics for type-safe to offer fully typed advice
A new bean pointcut element for matching specific named beans
Explicit support for AspectJ load-time weaving
July 27, 2008
5
Spring Framework
Journey
Middle Tier
Tag based declaration of declarative transactions in XML
Full Websphere transaction management support
Ships with a JPA abstraction layer
Spring 2.5 supports OpenJPA 1.0
Supports full asynchronous JMS
Spring 2.5 supports JCA style message listeners
Added support for NamedParamtersJdbcTemplate
Added SimpleJdbcTemplate for Java 5+
Spring 2.5 extended functionality for SimpleJdbcTemplate
July 27, 2008
6
Spring Framework
Journey
Web Tier
Introduced sensible defaulting via conventions-over-configuration
Spring Portlet framework which is conceptually similar to Spring MVC
Spring 2.5 supports annotation based controllers
A full featured JSP tag library
Spring 2.5 adds support for Tiles 2.0
Spring 2.5 adds support for JSF 1.2
Spring 2.5 fully supports JAX-WS 2.0/2.1
July 27, 2008
7
Spring Framework
Journey
Everything else
Dynamic Language Support
Spring 2.5 introduces Spring TestContext framework
Annotation-driven integration and unit testing framework
Supports JUnit 3.8, JUnit 4.4 and TestNG 5.5
Support for JMX Notifications, declarative control over registration behaviour
Spring 2.5 allows deployment of Spring application context as JCA resource
adapter, packaged as a JCA RAR file
Offers Thread Pooling
Adds more support for Java 5
July 27, 2008
8
Spring Framework
02 Data Access
July 27, 2008
9
Spring Framework
Problem with JDBC Code
public void insertPerson(Person person) throws Exception {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement("insert into person (id, firstName, lastName) values (?, ?, ?)");
stmt.setInt(0, person.getId().intValue());
stmt.setString(1, person.getFirstName());
stmt.setString(2, person.getLastName());
stmt.executeUpdate();
} catch(SQLException e) {
// error handler
} finally {
try {
if (stmt != null)
stmt.close();
} catch(SQLException e) { //error handler }
try {
if (conn != null)
conn.close();
} catch(SQLException e) { //error handler }
}
}
July 27, 2008
10
Spring Framework
Resource Management Problem
To access data source application must,
Establish a connection
To start its work application must,
Begin a transaction
When complete application must,
Commit or Rollback the transaction
Close the connection
July 27, 2008
11
Spring Framework
Database Access
makes JDBC easier to use and less error prone
framework handles the creation and release of resources
framework takes care of all the exceptions
translates SQLException to DataAccessException hierarchy
(runtime/unchecked exception)
generic, more informative, DB/JDBC independent
removes coupling with a particular persistence implementation
wraps all fine-grained exceptions
Developers are not forced to handle DataAccessException
July 27, 2008
12
Spring Framework
Resource Management Problem
Spring manages resources for you,
Reduces bolier-plate code
Reduce likelihood of bugs
Acquisition of the connection
Participation in the transaction
Execution of the statement
Processing of the result set
Handling of any exception
Release of the connection
July 27, 2008
13
Spring Framework
DAO Support
Abstraction for supported technologies,
JdbcDaoSupport
Provides a JdbcTemplate using a DataSource
HibernateDaoSupport*
Provides a HibernateTemplate using a SessionFactory
JdoDaoSupport
Provides a JdoTemplate using a PersistenceManagerFactory
JpaDaoSupport
Provides a JpaTemplate using a EntityManagerFactory
July 27, 2008
14
Spring Framework
02 Data Access
via JDBC
July 27, 2008
15
Spring Framework
JDBC Templates
Execute SQL queries, update statements or stored procedure calls
Iteration over ResultSets and extraction of returned parameter values
Types,
JdbcTemplate
NamedParamterJdbcTemplate
SimpleJdbcTemplate*
* Supported in Java 5+, supports varargs, and auto-boxing
July 27, 2008
16
Spring Framework
JdbcTemplate Usage
usage,
JdbcTemplate template = new JdbcTemplate(myDataSource);
Wiring,
<bean id=“jdbcTemplate” class=“org.springframework.jdbc.core.JdbcTemplate”>
<property name=“dataSource” ref=“dataSource” />
</bean>
<bean id=“personDao” class=“PersonDao”>
<property name=“jdbc” ref=“jdbcTemplate” />
</bean>
July 27, 2008
17
Spring Framework
JdbcTemplate – Examples
jdbc.execute(“drop table PERSONS”);
jdbc.update(“update PERSONS set FIRSTNAME=? where LASTNAME=?”,
new String[] { “Sandeep”, “Gupta” } );
jdbc.queryForInt(“select max(AGE) from PERSONS”);
(String) jdbc.queryForObject(“select FIRSTNAME from PERSONS where
LASTNAME=‘Gupta’ ”, String.class);
jdbc.queryForList(“select EMPNO, FIRSTNAME, LASTNAME from PERSONS”); *
* returns an arraylist, elements of which are an entry of a HashMap
July 27, 2008
18
Spring Framework
JdbcTemplate – Examples
jdbc.query("select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE",
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Employee e = new Employee();
e.setEmpNo(rs.getString(1));
e.setFirstName(rs.getString(2));
e.setLastName(rs.getString(3));
employees.add(e);
}
} );
July 27, 2008
19
Spring Framework
JdbcTemplate – Examples
jdbc.call(new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection conn) throws SQLException {
return conn.prepareCall("my query");
}
}, params);
BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
//...
}
public int getBatchSize() {
return ...;
}
};
jdbc.batchUpdate("update ...", setter);
July 27, 2008
20
Spring Framework
JdbcTemplate – Examples
Person person = (Person) jdbc.queryForObject(
“select first_name, last_name from persons where id = ?”,
new Object[] { new Long(1234) },
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SqlException {
Person p = new Person();
p.setFirstName(rs.getString(“first_name”));
p.setLastName(rs.getString(“last_name”));
return p;
}
} );
July 27, 2008
21
Spring Framework
JdbcTemplate – Examples
Collection persons = jdbc.query (
“select first_name, last_name from persons”,
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SqlException {
Person p = new Person();
p.setFirstName(rs.getString(“first_name”));
p.setLastName(rs.getString(“last_name”));
return p;
}
} );
July 27, 2008
22
Spring Framework
NamedParameterJdbcTemplate – Example
String sql = “select count(*) from persons where first_name = :first_name”;
SqlParameterSource namedParameters = new MapSqlParameterSource(“first_name”, firstName);
return namedTemplate.queryForInt(sql, namedParameters);
// could be used via a normal Map Collection
Map namedParameters = Collections.singletonMap(“first_name”, firstName);
// another way is to use BeanPropertySqlParameterSource
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(person);
July 27, 2008
23
Spring Framework
02 Data Access
via ORM
July 27, 2008
24
Spring Framework
ORM Support
Spring supports,
Sun’s standard persistence API JDO
Java Persistence API (JPA)
Hibernate
Apache OJB
iBATIS SQL Maps
Oracle Toplink
Provides additional services,
Integrated Transaction management
Exception handling
Thread-safe, lightweight template classes
Resource management
July 27, 2008
25
Spring Framework
Classic Hibernate Example
the value object,
public class Student {
private Integer id;
private String firstName;
private String lastName;
private Set courses;
//usual getters & setters
}
July 27, 2008
26
Spring Framework
Classic Hibernate Example
the mapping file,
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN“
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name=“spring.hibernate.Student">
<id name="id">
<generator class="assigned"/>
</id>
<property name=“firstName"/>
<property name=“lastName"/>
<set name="courses" table="transcript">
<key column="student_id"/>
<many-to-many column="course_id“class=“spring.hibernate.Course"/>
</set>
</class>
</hibernate-mapping>
July 27, 2008
27
Spring Framework
Classic Hibernate Example
hitting the database
public Student getStudent(Integer id) throws HibernateException {
Session session = sessionFactory.openSession();
Student student = (Student) session.load(Student.class, id);
session.close();
return student;
}
July 27, 2008
28
Spring Framework
Why Spring with Hibernate?
single instance of Session Factory
use spring configuration instead of hibernate.properties
load multiple .hbm.xml files
load all *.hbm.xml files from a directory folder
provides thread-safe HibernateTemplate class
support for HibernateDaoSupport class
July 27, 2008
29
Spring Framework
Wiring Hibernate
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value=”java:comp/env/jdbc/myDatasource” />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
July 27, 2008
30
Spring Framework
Wiring Hibernate
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>mapping1.hbm.xml</value>
<value>mapping2.hbm.xml</value>
</list>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/spring/hibernate/mappings</value>
</list>
</property>
</bean>
July 27, 2008
31
Spring Framework
HibernateTemplate – Examples
List employees = hibernate.find("from app.Employee");
List list = hibernate.find("from app.Employee e where e.lastName=?", “Gupta",
Hibernate.STRING);
List list = hibernate.find("from app.Employee e where e.lastName=? and e.firstName=?", new
String[] { “Sandeep", “Gupta" }, new Type[] {Hibernate.STRING , Hibernate.STRING });
List list = (List) hibernate.execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
List result = session.find("from app.Employee");
// do some further stuff with the result list
return result;
}
});
July 27, 2008
32
Spring Framework
Wiring JDO
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="myPmf" class="org.jpox.PersistenceManagerFactoryImpl" destroy-method="close">
<property name="connectionFactory" ref="dataSource"/>
<property name="nontransactionalRead" value="true"/>
</bean>
</beans>
July 27, 2008
33
Spring Framework
Wiring Oracle Toplink
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.toplink.LocalSessionFactoryBean">
<property name="connectionFactory" ref="dataSource"/>
<property name="configLocation" value="toplink-sessions.xml"/>
</bean>
</beans>
July 27, 2008
34
Spring Framework
Wiring iBATIS SQL Maps
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="connectionFactory" ref="dataSource"/>
<property name="configLocation" value="WEB-INF/sqlmap-config.xml"/>
</bean>
</beans>
July 27, 2008
35
Spring Framework
Wiring JPA
LocalEntityManagerFactoryBean – uses JPA PersistenceProvider auto-detection mechanism
<beans>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPersistenceUnit"/>
</bean>
</beans>
EntityManagerFactory using the JNDI
<beans>
<jee:jndi-lookup id="myEmf" jndi-name="persistence/myPersistenceUnit"/>
</beans>
July 27, 2008
36
Spring Framework
Wiring JPA
LocalContainerEntityManagerFactoryBean
<beans>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="someDataSource"/>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
</beans>
July 27, 2008
37
Spring Framework
Wiring JPA – Mulitple Persistence Units
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation">
<list>
<value>org/springframework/orm/jpa/domain/persistence-multi.xml</value>
<value>classpath:/my/package/**/custom-persistence.xml</value>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="localDataSource" value-ref="local-db"/>
<entry key="remoteDataSource" value-ref="remote-db"/>
</map>
</property>
<!-- if no datasource is specified, use this one -->
<property name="defaultDataSource" ref="remoteDataSource"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="pum"/>
</bean>
July 27, 2008
38
Spring Framework
02 Data Access
Transactions
July 27, 2008
39
Spring Framework
Transactions
can be described as ACID
Atomic
Consistent
Isolated
Durable
Global Transactions
Managed by application server, using JTA
Ability to work with multiple transactional resources
Local Transactions
Resource specific
Cannot run inside a global JTA container
Cannot work across multiple transactional resources
Global and Local transactions have different programming models
July 27, 2008
40
Spring Framework
Spring’s Solution
Provides same programming model
Provides different transaction management strategies in different
environments
Transaction management can be
Programmatic
Declarative (like EJB CMT)
for Declarative transactions, provides a TransactionProxyFactoryBean
* EJB CMT: EJB Container Managed Transactions
July 27, 2008
41
Spring Framework
Transaction Abstraction
Interface PlatformTransactionManager
getTransaction(TransactionDefinition)
commit(TransactionStatus)
rollback(TransactionStatus)
Transaction Definition
Isolation
Propogation
Read-only
Time-out
Transaction Status
isNewTransaction()
setRollBackOnly()
isRollBackOnly()
July 27, 2008
42
Spring Framework
Built-in Transaction Managers
JtaTransactionManager
DataSourceTransactionManager
HibernateTransactionManager
JdoTransactionManager
PersistenceBrokerTransactionManager (Apache OJB)
July 27, 2008
43
Spring Framework
Defining Transactions
JDBC Transaction
<bean id=“transactionManager”
class=“org.springframework.jdbc.datasource.DataSourceTransactionManager”>
<property name=“dataSource” ref=“myDataSource” />
</bean>
Hibernate Transaction
<bean id=“transactionManager”
class=“org.springframework,orm.hibernate.HibernateTransactionManager”>
<property name=“sessionFactory” ref=“mySessionFactory” />
</bean>
JDO Transaction
<bean id=“transactionManager” class=“org.springframework.orm.jdo.JdoTransactionManager”>
<property name=“persistenceManagerFactory” ref=“myPersistenceManagerFactory” />
</bean>
July 27, 2008
44
Spring Framework
Programmatic Transaction Management
Two ways,
Using TransactionTemplate
Using PlatformTransactionManager
TransactionTemplate
Uses general default settings
Code to be executed passed as,
TransactionCallback
TransactionCallbackWithoutResult
PlatformTransactionManager
Gives total control over TransactionTemplate, TransactionDefinition, and
TransactionStatus
July 27, 2008
45
Spring Framework
Transaction Template Usage
execute() of the template,
public void uploadMappings() {
transactionTemplate.execute( new TransactionCallBack() {
public Object doInTransaction(TransactionStatus ts) {
try {
//store the file in the archive table
//upload to synch table
//now transfer data from synch data to master table
} catch (Exception e) {
ts.setRollBackOnly();
}
return null;
}
} );
}
July 27, 2008
46
Spring Framework
Declarative Transaction Management
Made possible by use of Spring AOP and transactional aspects in a boiler
plate fashion.
Key differences with EJB CMT,
EJB CMT is tied to JTA – Spring can work with any
Spring enables DTM to any class and not just special one’s (EJBs)
Spring offers declarative RollBack rules – no equivalent in EJB CMT
Spring provides opportunity to customize transactional behaviour
Spring does not support propagation of transaction contexts across
remote calls.
July 27, 2008
47
Spring Framework
Declarative Transaction Management
Lifecycle,
Caller
July 27, 2008
AOP Proxy
Transaction
Advisor
Custom
Advisor(s)
Target
Method
48
Spring Framework
03 Integration
July 27, 2008
49
Spring Framework
03 Integration
Remoting & Webservices
July 27, 2008
50
Spring Framework
Remoting
Remoting is a conversation between a client application & a service hosted
somewhere else.
Remoting technologies available to a Java developer
Remote Method Invocation (RMI)
Caucho’s Hessian and Burlap
Enterprise JavaBeans (EJB)
JAX-RPC (J2EE 1.4’s web service API)
JAX-WS (successor of JAX-RPC, in JEE 5 and 6)
Java Messaging Service (JMS)
Spring’s own HTTP invoker
RMI was introduced in JDK 1.1. Before this CORBA (Common Object
Request Broker Architecture) was the only method available.
Spring wraps java.rmi.RemoteException and throws it as
org.springframework.remoting.RemoteAccessException
July 27, 2008
51
Spring Framework
RMI – Exposing a service
<bean id="accountService" class=“spring.AccountServiceImpl">
<!-- any additional collaborators, maybe a DAO? -->
</bean>
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<!-- does not necessarily have to be the same name as the bean to be exported -->
<property name="serviceName" value="AccountService"/>
<property name="service" ref="accountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
<!-- defaults to 1099 -->
<property name="registryPort" value="1199"/>
</bean>
July 27, 2008
52
Spring Framework
RMI – Consuming a service
<bean class=“spring.SimpleObject">
<property name="accountService" ref="accountService"/>
</bean>
<bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://HOST:1199/AccountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
</bean>
July 27, 2008
53
Spring Framework
Hessian/Burlap
Use HTTP for transportation
Wiring HTTP servlet,
<servlet>
<servlet-name>remoting</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>remoting</servlet-name>
<url-pattern>/remoting/*</url-pattern>
</servlet-mapping>
July 27, 2008
54
Spring Framework
Hessian/Burlap – Exposing a service
<bean id="accountService" class=“spring.AccountServiceImpl">
<!-- any additional properties, maybe a DAO? -->
</bean>
<bean name="/AccountService" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
</bean>
July 27, 2008
55
Spring Framework
Hessian/Burlap – Consuming a service
<bean class=“spring.SimpleObject">
<property name="accountService" ref="accountService"/>
</bean>
<bean id="accountService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
</bean>
July 27, 2008
56
Spring Framework
Hessian/Burlap – Wiring without MVC
<servlet>
<servlet-name>accountExporter</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>accountExporter</servlet-name>
<url-pattern>/remoting/AccountService</url-pattern>
</servlet-mapping>
<bean name="accountExporter" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
</bean>
July 27, 2008
57
Spring Framework
HTTP Invoker – Exposing a service
<bean name="/AccountService"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
</bean>
Or,
<bean name="accountExporter"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<!-- other collaborators -->
</bean>
<servlet>
<servlet-name>accountExporter</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>accountExporter</servlet-name>
<url-pattern>/remoting/AccountService</url-pattern>
</servlet-mapping>
July 27, 2008
58
Spring Framework
HTTP Invoker – Consuming a service
<bean id="httpInvokerProxy"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>
<property name="serviceInterface" value=“spring.AccountService"/>
</bean>
July 27, 2008
59
Spring Framework
HTTP Invoker – Switching HTTP Client
By default, it uses J2SE Http functionality.
Change to Apache Commons HTTP client by,
<property name="httpInvokerRequestExecutor">
<bean class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor"/>
</property>
July 27, 2008
60
Spring Framework
JAX-RPC v/s JAX-WS
JAX-WS still supports SOAP 1.1 over HTTP 1.1 and WSDL 1.1
JAX-WS also supports SOAP 1.2
JAX-WS adds support for WSDL 1.1 HTTP bindings
JAX-RPC supports WS-I BP version 1.0, JAX-WS supports WS-I BP 1.1
JAX-WS maps to Java 5
JAX-RPC has its own data mapping model, JAX-WS uses the standard JAXB
JAX-WS introduces asynchronous functionality
JAX-WS introduces message-oriented functionality
JAX-WS introduces dynamic asynchronous functionality
JAX-WS adds support for Message Transmission Optimization Mechanism (MTOM), the new
attachment specification
JAX-RPC handlers rely on SAAJ 1.2, JAX-WS handlers rely on SAAJ 1.3
* WS-I: Web Services Interoperability Organization
* SAAJ: SOAP with Attachments API for Java
July 27, 2008
61
Spring Framework
JAX-RPC – Exposing a service
Implement ServletEndpointSupport and register this with RPC server
public class AccountServiceEndpoint extends ServletEndpointSupport implements
RemoteAccountService {
private AccountService biz;
protected void onInit() {
this.biz = (AccountService) getWebApplicationContext().getBean("accountService");
}
public void insertAccount(Account acc) throws RemoteException {
biz.insertAccount(acc);
}
public Account[] getAccounts(String name) throws RemoteException {
return biz.getAccounts(name);
}
}
July 27, 2008
62
Spring Framework
JAX-RPC – Accessing a service
LocalJaxRpcServiceFactoryBean and JaxRpcPortProyFactoryBean
<bean id="accountWebService"
class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
<property name="serviceInterface" value=“spring.RemoteAccountService"/>
<property name="wsdlDocumentUrl"
value="http://localhost:8080/account/services/accountService?WSDL"/>
<property name="namespaceUri" value="http://localhost:8080/account/services/accountService"/>
<property name="serviceName" value="AccountService"/>
<property name="portName" value="AccountPort"/>
</bean>
To get rid of RemoteException,
<bean id="accountWebService"
class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
<property name="serviceInterface" value=“spring.AccountService"/>
<property name="portInterface" value=“spring.RemoteAccountService"/>
</bean>
July 27, 2008
63
Spring Framework
JAX-WS – Exposing a service
For Java 5,
@WebService(serviceName="AccountService")
public class AccountServiceEndpoint extends SpringBeanAutowiringSupport {
@Autowired
private AccountService biz;
@WebMethod
public void insertAccount(Account acc) {
biz.insertAccount(acc);
}
@WebMethod
public Account[] getAccounts(String name) {
return biz.getAccounts(name);
}
}
July 27, 2008
64
Spring Framework
JAX-WS – Exposing a service
Wiring,
<bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter">
<property name="baseAddress" value="http://localhost:9999/"/>
</bean>
<bean id="accountServiceEndpoint" class=“spring.AccountServiceEndpoint">
...
</bean>
July 27, 2008
65
Spring Framework
JAX-WS – Exposing a service
For Java 6,
@WebService(serviceName="AccountService")
public class AccountServiceEndpoint {
@Autowired
private AccountService biz;
@WebMethod
public void insertAccount(Account acc) {
biz.insertAccount(acc);
}
@WebMethod
public Account[] getAccounts(String name) {
return biz.getAccounts(name);
}
}
July 27, 2008
66
Spring Framework
JAX-WS – Accessing a service
<bean id="accountWebService"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
<property name="serviceInterface" value=“spring.AccountService"/>
<property name="wsdlDocumentUrl"
value="http://localhost:8080/account/services/accountService?WSDL"/>
<property name="namespaceUri" value="http://localhost:8080/account/services/accountService"/>
<property name="serviceName" value="AccountService"/>
<property name="portName" value="AccountPort"/>
</bean>
July 27, 2008
67
Spring Framework
03 Integration
Enterprise Java Beans
July 27, 2008
68
Spring Framework
Spring and JSR-250
JSR-250 provides a set of common annotations for use in JavaEE apps
Helps avoid proliferation of framework-specific annotations
Facilitates portability
Used by EJB 3.0
support starting Spring 2.5
All annotations in javax.annotation package
Included in JDK 6
Available as javaee-api.jar in JDK 5
Examples, @PostConstruct, @PreDestroy, @Resource
Spring uses these to trigger life-cycle events.
July 27, 2008
69
Spring Framework
Accessing Stateless Session Beans
Using a local slsb,
<bean id=“myEJB" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName" value="ejb/myEJB"/>
<property name="businessInterface" value=“spring.ejb.MyEJB"/>
</bean>
<bean id=“myWebController" class=“spring.MyWebController">
<property name="myComponent" ref="myComponent"/>
</bean>
July 27, 2008
70
Spring Framework
Accessing Stateless Session Beans
Using a remote slsb,
<bean id="myComponent"
class="org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean">
<property name="jndiName" value="ejb/myBean"/>
<property name="businessInterface" value="com.mycom.MyComponent"/>
<property name="jndiEnvironment">
<props>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
<prop key="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</prop>
<prop key="java.naming.provider.url">jnp://localhost:1099</prop>
</props>
</property>
</bean>
<bean id=“myWebController" class=“spring.MyWebController">
<property name="myComponent" ref="myComponent"/>
</bean>
July 27, 2008
71
Spring Framework
Accessing Statefull Session Beans
No proxy classes are available :(
<bean id="counterServiceHome"class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="ejb/counterService" />
<property name="resourceRef" value="true" />
</bean>
try {
CounterServiceHome home = (CounterServiceHome) ctx.getBean("counterServiceHome");
service = (CounterService) home.create();
service.doSomething();
} catch (CreateException ex) {
// log error
}
July 27, 2008
72
Spring Framework
Writing EJBs
Spring has no magic for EJB proxying :(
Offers you to write Spring-enabled EJBs
Using Spring’s EJB support classes,
AbstractStatelessSessionBean
AbstractStatefullSessionBean
AbstractMessageDrivenBean
AbstractJmsMessageDrivenBean
Advantages,
Provides default implementation to EJB life-cycle methods: ejbActivate(),
ejbPassivate(), ejbRemove()
Provides access to Spring Bean Factory
July 27, 2008
73
Spring Framework
Writing EJBs – Example
public class CourseServiceEjb extends AbstractStatelessSessionBean implements CourseService {
private CourseService courseService;
protected void onEjbCreate() {
courseService = (CourseService) getBeanFactory().getBean("courseService");
}
public void createCourse(Course course) {
courseService.createCourse(course);
}
public Set getAllCourses() {
return courseService.getAllCourses();
}
}
Retrieves the bean factory via the BeanFactoryLocator, whose default
implementation is ContextJndiBeanFactory.
Loads as a JNDI variable java:comp/env/ejb/BeanFactoryPath
July 27, 2008
74
Spring Framework
Writing EJBs – Example
To have a single copy of the ApplicationContext with all EJBs.
To load from a particular JNDI variable
public void setSessionContext(SessionContext sessionContext) {
super.setSessionContext(sessionContext);
setBeanFactoryLocator(ContextSingletonBeanFactoryLocator.getInstance());
setBeanFactoryLocatorKey(“businessBeanFactory”);
}
<beans>
<bean id="businessBeanFactory"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg value="businessApplicationContext.xml" />
</bean>
</beans>
July 27, 2008
75
Spring Framework
03 Integration
JMS
July 27, 2008
76
Spring Framework
Introduction
Provides a JmsTemplate
Shields user from differences of JMS 1.0.2 and 1.1 APIs
Use JmsTemplate for JMS 1.1 API
Use JmsTemplate102 for JMS 1.0.2 API
Provides message listener containers to create Message-Driven POJOs
(MDPs)
Converts checked JMSException hierarchy to mirrored unchecked
exceptions hierarchy
Provides MessageConverter abstraction to convert between objects and
JMS messages
Support for JCA Message Endpoints
July 27, 2008
77
Spring Framework
Configuring
A very simple JNDI configuration,
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName"><value>jms/connectionFactory</value></property>
<property name="resourceRef"><value>true</value></property>
</bean>
<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName"><value>jms/queue</value></property>
<property name="resourceRef"><value>true</value></property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory“ ref=“connectionFactory"/>
<property name="defaultDestination“ ref="destination"/>
<property name="receiveTimeout“ value=“30000” />
</bean>
July 27, 2008
78
Spring Framework
Sending a Message
The normal POJO class,
public class JmsQueueSender {
private JmsTemplate jmsTemplate;
private Queue queue; // with the usual setter
public void setConnectionFactory(ConnectionFactory cf) {
this.jmsTemplate = new JmsTemplate(cf, false);
}
public void simpleSend() {
this.jmsTemplate.send(this.queue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("hello queue world");
}
});
}
}
July 27, 2008
79
Spring Framework
Receiving a Message
The normal JMS class,
public class MyJMSListener implements MessageListener {
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
}
catch (JMSException ex) {
throw new RuntimeException(ex);
}
}
else {
throw new IllegalArgumentException("Message must be of type TextMessage");
}
}
}
July 27, 2008
80
Spring Framework
Receiving a Message
Wiring,
<bean id="messageListener" class=“spring.MyJMSListener" />
<!-- and this is the message listener container -->
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="messageListener" />
</bean>
July 27, 2008
81
Spring Framework
Session Awareness
Using SessionAwareMessageListener,
package org.springframework.jms.listener;
public interface SessionAwareMessageListener {
void onMessage(Message message, Session session) throws JMSException;
}
* throws JMSException – onus of handling it lies in client code.
July 27, 2008
82
Spring Framework
Message Driven POJOs
MessageListenerAdapter,
public interface MessageDelegate {
void handleMessage(String message);
void handleMessage(Map message);
void handleMessage(byte[] message);
void handleMessage(Serializable message);
}
public class DefaultMessageDelegate implements MessageDelegate {
// implementation elided for clarity...
}
July 27, 2008
83
Spring Framework
Message Driven POJOs
Realizing the power,
<!-- this is the Message Driven POJO (MDP) -->
<bean id="messageListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<bean class=“spring.DefaultMessageDelegate"/>
</constructor-arg>
</bean>
<!-- and this is the message listener container... -->
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="messageListener" />
</bean>
July 27, 2008
84
Spring Framework
03 Integration
JMX
July 27, 2008
85
Spring Framework
Introduction
Provides four core features,
Automatic registration of any Spring bean as a JMX bean
Flexible mechanism for controlling the management interface of your beans
Declarative exposure of MBeans over remote, JSR-160 connectors
Simple proxying of both local and remote MBean resources
July 27, 2008
86
Spring Framework
Exporting Beans to JMX
<!-- bean must not be lazily initialized if the exporting is to happen -->
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="beans">
<map>
<entry key="bean:name=testBean1" value-ref="testBean"/>
</map>
</property>
</bean>
<!– a simple POJO bean with getters/setters for properties -->
<bean id="testBean" class=“spring.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
* assumes app is running in an environment that has only ONE MBean server running
July 27, 2008
87
Spring Framework
Creating an MBeanServer
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<!– bean must be eager-initialized -->
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=testBean1" value-ref="testBean"/>
</map>
</property>
<property name="server" ref="mbeanServer"/>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
July 27, 2008
88
Spring Framework
Reusing an MBeanServer
The MBeanExporter automatically detects a running MBeanServer.
In case of multiple running servers,
pass the server as an argument to the MBeanExporter
In case MBeanServer has a dynamic ID, use factory lookup method,
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="server">
<!-- Custom MBeanServerLocator -->
<bean class="platform.package.MBeanServerLocator" factory-method="locateMBeanServer"/>
</property>
<!-- other collaborators here -->
</bean>
July 27, 2008
89
Spring Framework
Advanced Concepts
Automatic registration,
<bean name="spring:mbean=true" class="org.springframework.jmx.export.TestDynamicMBean"/>
JSR-160 Connectors
Server-side connectors,
<bean id="serverConnector" class="org.springframework.jmx.support.ConnectorServerFactoryBean">
<property name="objectName" value="connector:name=rmi"/>
<property name="serviceUrl"
value="service:jmx:rmi://localhost/jndi/rmi://localhost:1099/myconnector"/>
</bean>
Client-side connectors,
<bean id="clientConnector"
class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean">
<property name="serviceUrl" value="service:jmx:rmi://localhost:9875"/>
</bean>
July 27, 2008
90
Spring Framework
03 Integration
Email
July 27, 2008
91
Spring Framework
Introduction
MailSender
value object encapsulating simple mail properties
JavaMailSender
adds support for MIME messages, attachments and inline resources
Velocity
support for Velocity based-templating of messages.
July 27, 2008
92
Spring Framework
Basic Emailing
Coding the Java part,
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
msg.setTo(order.getCustomer().getEmailAddress());
msg.setText(
"Dear " + order.getCustomer().getFirstName()
+ order.getCustomer().getLastName()
+ ", thank you for placing order. Your order number is "
+ order.getOrderNumber());
try{
this.mailSender.send(msg);
}
catch(MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
}
July 27, 2008
93
Spring Framework
Basic Emailing
Wiring,
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="[email protected]"/>
<property name="subject" value="Your order"/>
</bean>
<bean id="orderManager" class=“spring.SimpleOrderManager">
<property name="mailSender" ref="mailSender"/>
<property name="templateMessage" ref="templateMessage"/>
</bean>
July 27, 2008
94
Spring Framework
MimeMessagePreparator
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress(order.getCustomer().getEmailAddress()));
mimeMessage.setFrom(new InternetAddress("[email protected]"));
mimeMessage.setText(“This is a simple Mail”);
}
};
try {
this.mailSender.send(preparator);
}
catch (MailException ex) {
System.err.println(ex.getMessage());
}
July 27, 2008
95
Spring Framework
Attachments
MimeMessage message = sender.createMimeMessage();
// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("[email protected]");
helper.setText("Check out this image!");
// let's attach the infamous windows Sample file (this time copied to c:/)
Resource file = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addAttachment("CoolImage.jpg", file);
sender.send(message)
July 27, 2008
96
Spring Framework
Inline Resources
MimeMessage message = sender.createMimeMessage();
// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("[email protected]");
// use the true flag to indicate the text included is HTML
helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
// let's include the infamous windows Sample file (this time copied to c:/)
Resources res = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addInline("identifier1234", res);
sender.send(message);
* The order in which resources and text are added is IMPORTANT, else it won’t work!
July 27, 2008
97
Spring Framework
Velocity Based Templating
Velocity Template,
<html>
<body>
<h3>Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!</h3>
<div>
Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.
</div>
</body>
</html>
July 27, 2008
98
Spring Framework
Velocity Based Templating
Java code,
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(user.getEmailAddress());
message.setFrom([email protected]"); // could be parameterized...
Map model = new HashMap();
model.put("user", user);
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "com/mycompany/registration-confirmation.vm", model);
message.setText(text, true);
}
};
this.mailSender.send(preparator);
July 27, 2008
99
Spring Framework
Velocity Based Templating
Wiring,
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.csonth.gov.uk"/>
</bean>
<bean id="registrationService" class=“spring.SimpleRegistrationService">
<property name="mailSender" ref="mailSender"/>
<property name="velocityEngine" ref="velocityEngine"/>
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>
July 27, 2008
100
Spring Framework
03 Integration
Scheduling
July 27, 2008
101
Spring Framework
Quartz Scheduler
Using the JobDetailBean,
public class ExampleJob extends QuartzJobBean
{
private int timeout;
public void setTimeout(int timeout) {
this.timeout = timeout;
}
protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
// do the actual work
}
}
July 27, 2008
102
Spring Framework
Quartz Scheduler
Using the JobDetailBean,
<bean name=“quartzJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value=“spring.QuartzJob" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="5" />
</map>
</property>
</bean>
July 27, 2008
103
Spring Framework
Quartz Scheduler
Using a POJO via MethodInvokingJobDetailFactoryBean,
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref=“myPojoJob" />
<property name="targetMethod" value="doIt" />
</bean>
<bean id=“myPojoJob" class=“spring.MyPojoJob"/>
public class MyPojoJob {
// properties and collaborators
public void doIt() {
// do the actual work
}
}
July 27, 2008
104
Spring Framework
Quartz Scheduler
Using Triggers & SchedulerFactory,
<bean id="simpleTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="jobDetail" />
<property name="startDelay" value="10000" />
<property name="repeatInterval" value="50000" />
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="exampleJob" />
<property name="cronExpression" value="0 0 6 * * ?" />
</bean>
July 27, 2008
105
Spring Framework
Quartz Scheduler
Using Triggers & SchedulerFactory,
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
<ref bean="simpleTrigger" />
</list>
</property>
</bean>
July 27, 2008
106
Spring Framework
JDK Timer
Using a Custom Timer,
public class CheckEmailAddresses extends TimerTask {
private List emailAddresses;
public void setEmailAddresses(List emailAddresses) {
this.emailAddresses = emailAddresses;
}
public void run() {
// iterate over all email addresses and archive them
}
}
July 27, 2008
107
Spring Framework
JDK Timer
Using a Custom Timer,
<bean id="checkEmail" class=“spring.CheckEmailAddress">
<property name="emailAddresses">
<list>
<value>[email protected]</value>
<value>[email protected]</value>
</list>
</property>
</bean>
<bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="10000" />
<property name="period" value="50000" />
<property name="timerTask" ref="checkEmail" />
</bean>
July 27, 2008
108
Spring Framework
JDK Timer
Start actual scheduling,
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<!-- see the example above -->
<ref bean="scheduledTask" />
</list>
</property>
</bean>
July 27, 2008
109
Spring Framework
JDK Timer
Using a POJO via MethodInvokingTimerTaskFactoryBean,
<bean id="doIt" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref=“myTimerPOJO" />
<property name="targetMethod" value="doIt" />
</bean>
public class MyTimerPOJO {
// properties and collaborators
public void doIt() {
// do the actual work
}
}
July 27, 2008
110
Spring Framework
03 Integration
Thread Pooling
July 27, 2008
111
Spring Framework
Thread Pooling
Introduced with Spring 2.0+
Executors – are Java 5 name for concept of thread pools.
Spring’s TaskExecutor is identical to Java’s Executor interface,
Was introduced to abstract away the need for Java 5 while using Thread pools.
Spring’s own components such as ApplicationEventMulticaster, Quartz
integration, JMS’s AbstractMessageListenerContainer all use this abstraction.
July 27, 2008
112
Spring Framework
Task Executors
Number of pre-built implementations,
SimpleAsyncTaskExecutor
starts up a new thread for each invocation, supports pool limit
SyncTaskExecutor
executes invocations synchronously in the calling thread.
ConcurrentTaskExecutor
wrapper over Java 5 Executor
SimpleThreadPoolTaskExecutor
subclass of Quartz’s SimpleThreadPool, listens to Spring’s lifecycle callbacks
July 27, 2008
113
Spring Framework
Task Executors
Number of pre-built implementations,
ThreadPoolTaskExecutor
available only in Java 5+, exposes bean properties for configuring
TimerTaskExecutor
uses TimerTask as backing implementation, method invocations are executed
in a separate thread, although they are synchronous
WorkManagerTaskExecutor
uses CommonJ WorkManager as its backing implementation, acts as a
convenience class for setting up CommonJ WorkManager reference in context
July 27, 2008
114
Spring Framework
Usage,
Create a executor class,
public class TaskExecutorExample {
private class MessagePrinterTask implements Runnable {
private String message; // wired via constructor
public void run() {
System.out.println(message);
}
}
private TaskExecutor taskExecutor; // wired using contructor
public void printMessages() {
for(int i = 0; i < 25; i++) {
taskExecutor.execute(new MessagePrinterTask("Message" + i));
}
}
}
July 27, 2008
115
Spring Framework
Usage,
Wiring,
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>
<bean id="taskExecutorExample" class=“spring.TaskExecutorExample">
<constructor-arg ref="taskExecutor" />
</bean>
July 27, 2008
116
Spring Framework
03 Integration
Dynamic Language Support
July 27, 2008
117
Spring Framework
Dynamic Language Support
Introduced with Spring 2.0
Supported languages,
JRuby 0.9 / 1.0
Groovy 1.0 / 1.5
BeanShell 2.0
<lang:language /> element,
<lang:jruby />
<lang:groovy />
<lang:bsh />
July 27, 2008
118
Spring Framework
Groovy – A quick Example
The java interface,
package spring.dls.groovy;
public interface EmailService {
public void sendMail(EmailValueObject email);
}
Class using this service,
package spring.dls.groovy.usage;
public class ReminderServiceImpl implements ReminderService {
private EmailService emailService;
// usual getters/setters
public void sendReminder(ReminderValueObject reminder) {
// do some stuff
emailService(reminder.getReminderEmail());
}
}
July 27, 2008
119
Spring Framework
Groovy – A quick Example
The groovy implementation,
// from the file ‘GroovyEmailService.groovy'
package spring.dls.groovy;
// import the Messenger interface (written in Java) that is to be implemented
import spring.dls.groovy.EmailService;
// define the implementation in Groovy
class GroovyEmailService implements EmailService {
// implementation of the various stubs
}
July 27, 2008
120
Spring Framework
Groovy – A quick Example
Gluing,
<beans>
<!-- this is the bean definition for the Groovy-backed EmailService implementation -->
<lang:groovy id=“emailService" script-source="classpath:GroovyEmailService.groovy">
<lang:property name=“smtp" value=“smtp.myserver.com" />
</lang:groovy>
<!-- an otherwise normal bean that will be injected by the Groovy-backed Email Service Impl -->
<bean id=“reminderService" class=“spring.dls.groovy.usage.ReminderServiceImpl">
<property name=“emailService" ref=“emailService" />
</bean>
</beans>
July 27, 2008
121
Spring Framework
References & Feedback
July 27, 2008
122
Spring Framework
References
Websites
http://www.springframework.org
http://martinfowler.com/articles/injection.html
http://docs.codehaus.org/display/PICO/Inversion+of+Control
http://static.springframework.org/spring/docs/2.5.5/reference/index.html
http://www.theserverside.com/articles/article.tss?l=SpringFramework
http://www.ibm.com/developerworks/library/j-aopwork1/
Books
Spring In Action by Craig Walls and Ryan Breidenbach
Spring j2ee Application Framework by Spring Development Team
J2EE Without EJB by Rod Johnson and Juergen Holler
Spring Live by Matt Raible
July 27, 2008
123
Spring Framework
Questions
For any queries or suggestions,
Post it on,
http://azcarya.googlecode.com
Drop me a mail at,
[email protected]
July 27, 2008
124
Hope this helps.
SANDEEP GUPTA
© 2008, under Creative Commons 3.0 Attribution License
July 27, 2008
125
Descargar

Spring Abstractions.ppsx