1
|
|
2
|
- Spring in Action
- Craig Walls and Ryan Breidenbach
- Professional Java Development with Spring
- Rod Johnson, Juergen Hoeller and Team
- Spring – www.springframework.org
- J2EE without EJB – Rod Johnson/ Jurgen Hoeller
- Better, Faster, Lighter Java – Bruce Tate
- Wiring your Web Application with Open Source Java http://www.onjava.com/pub/a/onjava/2004/04/07/wiringwebapps.html
|
3
|
- ACEGI Security - comprehensive security services for the Spring
Framework
- Spring IDE - graphical user interface for the configuration files used
by the Spring Framework
- Spring BeanDoc - tool that facilitates documentation and graphing of
Spring bean factories and application context files
- XDoclet Spring Tags - support for generating Spring XML config files
from annotations in Java classes (you could also use JDK1.5 annotations
to achieve this)
- Spring Web Flow - for web applications with demanding page flow
requirements
- AppFuse Not really a tool or add-on, but AppFuse is Matt Raible's
project to jumpstart your Java web projects. It uses Spring at it's core
and studying it is a great way to learn about Spring.
- Spring Framework .NET – Spring Clone for the Dark Side J
|
4
|
- The Official Spring Reference Manual
http://www.springframework.org/docs/reference/
- Introduction to Spring by Rod Johnson
- http://www.theserverside.com/articles/article.tss?l=SpringFramework
- Spring in Action by Craig Walls and Ryan Breidenbach
- Pro Spring by Rob Harrop and Jan Machacek
- J2EE Without EJB by Rod Johnson and Juergen Holler
- Expert One-on-One J2EE Design and Development by Rod Johnson
- Spring Developers Notebook by Bruce Tate and Justin Gehtland
- Better, Faster, Lighter Java by Bruce Tate and Justin Gehtland
- Spring Live by Matt Raible
- Professional Java Development with the Spring Framework
- by many of the core Spring developers: Coming in July 2005
|
5
|
|
6
|
|
7
|
- Uma camada de abstração para persistência de dados utilizando um ou mais
das seguintes tecnologias
- JDBC
- Hibernate, OJB
- JDO
- iBatis
- Uma robusta infra-estrutura para o gerenciamento de transações de forma
declarativa que suporta tanto transações locais como transações
distribuídas através da JTA
- Uma camada simplificadora para tecnologias de distribuição incluindo
EJBs, RMI, e Web Services
- Útil suporte a JNDI, JMS, email, e agendamento de tarefas(task
scheduling)
|
8
|
- Possui uma API de acesso a dados que ajuda a isolar e melhorar o modo
como o dado é servido pela camada de negócio
- Mais uma consistente e rica hierarquia de exceções suficiente para
mapear exceções específicas dependentes de tecnologia para outras
exceções genéricas
- Além de uma série de templates e warpper classes para se trabalhar com
JDBC, Hibernate, JDO, etc.
|
9
|
|
10
|
|
11
|
|
12
|
|
13
|
- Consistent abstraction
- PlatformTransactionManager
- Does not reinvent transaction manager
- Choose between JTA, JDBC, Hibernate, JDO etc with simple changes to
configuration not Java code
- No more rewriting application to scale up from JDBC or Hibernate local
transactions to JTA global transactions
- Use the simplest transaction infrastructure that can possibly work
- Programmatic transaction management
- Simpler API than JTA
- Use the same API for JTA, JDBC, Hibernate etc.
- Write once have transaction management everywhereTM
|
14
|
- Most popular transaction management option
- Built on same abstraction as programmatic transaction management
- Declarative transaction management for any POJO, without EJB: even
without JTA (single database)
- More flexible than EJB CMT
- Declarative rollback rules: roll back on MyCheckedException
- Non-invasive: Minimizes dependence on the container
- No more passing around EJBContext
|
15
|
- Suporte para gerenciamento programático e declarativo de transações
- Transações locais são delegadas pelo Spring para o gerente de
transações do data-source
- Quando múltiplos recursos estão involvidos (transações distribuídas),
Spring delega para o gerente de transações JTA obtido através do JNDI
- Apenas algumas pequenas mudanças
são necessárias para trocar entre local e JTA
|
16
|
- Gerenciamento Declarativo (+)
- Usa AOP para encapsular chamadas a objetos transacionais com código de begin
e commit de transações
- Comportamento de propagação
- Mandatory, Never, Not Supported, Required, Requires New, Support,
Nested
- Similar a EJBs
- Também suporta níveis de isolação
- Default, Read Uncommitted, Read Committed, Repeatable Read,
Serializable
|
17
|
|
18
|
|
19
|
|
20
|
- public class ServiceImpl implements Service {
- private int timeout;
- private AccountDao accountDao;
- public void setTimeout(int
timeout) {
- this.timeout = timeout;
- }
- public void setAccountDao(AccountDao accountDao) {
- this.accountDao = accountDao;
- }
- public void doSomething() throws ServiceWithdrawnException {
- }
- }
- <bean id="serviceTarget"
class="com.mycompany.service.ServiceImpl">
- <property
name="timeout"><value>30</timeout></property>
- <property name="accountDao"><ref
local="accountDao"/></property>
- </bean>
|
21
|
- <bean id=“service"
class=“org.springframework.transaction.interceptor.TransactionProxyFactoryBean"/>
- <property name="target">
- <ref local="serviceTarget"/>
- </property>
- <property name="transactionManager">
- <ref local="localTransactionManager"/>
- </property>
- <property name="transactionAttributes">
- <props>
- <prop key="do*">
-
PROPAGATION_REQUIRED,-ServiceWithdrawnException
- </prop>
- </props>
- </property>
- </bean>
|
22
|
- Rollback rule means that we don’t need to call setRollbackOnly()
- Of course Spring also supports programmatic rollback
- Can run this from a JUnit test case
- Doesn’t depend on a heavyweight container
- Can work with JTA, JDBC, Hibernate, JDO, iBATIS transactions…
- Just change definition of transaction manager
|
23
|
- Alternative approaches, simpler in large applications:
- Use “auto proxy creator” to apply similar transaction attributes to
multiple beans
- Use metadata or another pointcut approach to apply transactional
behaviour to multiple classes
|
24
|
- Integrated with Spring transaction management
- Unique synergy
- Gestalt again…
- Doesn’t reinvent the wheel.
- There are good solutions for O/R mapping, we make them easier to use
- Out-of-the-box support for
- JDBC
- Hibernate
- JDO
- iBATIS
- Model allows support for other technologies (TopLink etc)
- Consistent DataAccessException hierarchy allows truly
technology-agnostic DAOs
|
25
|
|
26
|
- Extend your DAO classes with the proper xxxDAOSupport class that matches
your persistence mechanism.
- JdbcDaoSupport
- Super class for JDBC data access objects.
- Requires a DataSource to be set, providing a JdbcTemplate based on it
to subclasses.
- HibernateDaoSupport
- Super class for Hibernate data access objects.
- Requires a SessionFactory to be set, providing a HibernateTemplate
based on it to subclasses.
- JdoDaoSupport
- Super class for JDO data access objects.
- Requires a PersistenceManagerFactory to be set, providing a JdoTemplate
based on it to subclasses.
- SqlMapDaoSupport
- Supper class for iBATIS SqlMap data access object.
- Requires a DataSource to be set, providing a SqlMapTemplate
|
27
|
- Usando um template jdbc do spring
|
28
|
- Operações também podem ser modeladas como objetos
|
29
|
- Usando o objeto UpdateCustomer
|
30
|
- Built in code templates that support JDBC, Hibernate, JDO, and iBatis
SQL Maps
- Simplifies data access coding by reducing redundant code and helps avoid
common errors.
- Alleviates opening and closing connections in your DAO code.
- No more ThreadLocal or passing Connection/Session objects.
- Transaction management is handled by a wired bean
- You are dropped into the template with the resources you need for data
access – Session, PreparedStatement, etc.
- Code only needs to be implemented in callback methods.
- Optional separate JDBC framework
|
31
|
- public class OrderHibernateDAO implements IOrderDAO {
- public Order saveOrder(Order order) throws OrderException{
- Session s = null;
- Transaction tx = null;
- try{
- s = ... // get a new Session
object
- tx = s.beginTransaction();
- s.save(order);
- tx.commit();
- } catch (HibernateException he){
- // log, rollback, and convert to OrderException
- } catch (SQLException sqle){
- // log, rollback, and convert to OrderException
- } finally {
- s.close(); // needs a try/catch
block
- }
- return order;
- }
|
32
|
- public class OrderHibernateDAO extends HibernateDaoSupport
- implements IOrderDAO {
- ...
- public Order saveOrder(final Order order) {
- HibernateTemplate hib =
getHibernateTemplate();
- return (Order)hib.execute(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException, SQLException {
- session.save(order);
- return order;
- }
- });
- }
- ...
- }
|
33
|
- public class OrderHibernateDAO extends HibernateDaoSupport
- implements IOrderDAO {
- ...
- public List findOrdersByCustomerId(int id) {
- HibernateTemplate hib =
getHibernateTemplate();
- return hib.findByNamedQuery(“OrdersByCustomerID”,
- new Integer(id));
- }
- public Order findOrderById(int orderId ) {
- HibernateTemplate hib =
getHibernateTemplate();
- return (Order) hib.load(Order.class,
- new Integer(orderId));
- }
- ...
- }
|
34
|
- Class library offers simpler programming model than raw JDBC
- Two flavours of usage:
- Callbacks (JdbcTemplate)
- JDBC objects: Model queries, updates and stored procedures as objects
- No more try/catch/finally blocks
- No more leaked connections
- Spring will always close a connection: no scope for programmer error
- Meaningful exception hierarchy
- No more vendor code lookups
- Spring autodetects database and knows what Oracle, DB2 error codes
mean
- More portable code
- More readable code
- catch (BadSqlGrammarException ex)
- Stored procedure support
- Can refactor to clean up JDBC without adopting Spring overall
- Incremental adoption: Step by step
|
35
|
- Spring prove um bean SessionFactory que simplifica a configuração e o
gerênciamento de sessões em objetos de negócio
- Uma classe HibernateTemplate
- Uma classe HibernateDaoSupport que pode ser herdada para maior abstração
- Gerenciamento e mapeamento das HibernateException´s
- Facilmente plugável ao framework de Transações do Spring
|
36
|
|
37
|
- Exemplo de configuração (cont)
|
38
|
|
39
|
- Manages Hibernate sessions
- No more custom ThreadLocal sessions
- Sessions are managed within Spring transaction management
- Works with JTA if desired
- Works within EJB container with CMT if desired
- HibernateTemplate makes common operations easy
- Simpler, consistent exception handling
- Many operations become one-liners
- Less, simpler, code compared to using Hibernate alone
- Portability: Switch between Hibernate, JDO and other transparent
persistence technologies without changing DAO interfaces
- Can even switch to JDBC where transparent update is not implied
- Mixed use of Hibernate and JDBC within the same transaction
|
40
|
- public class MyHibernateDao implements MyDao {
- private HibernateTemplate hibernateTemplate;
- public MyHibernateDao (net.sf.hibernate.SessionFactory sessionFactory)
{
- hibernateTemplate = new HibernateTemplate(sessionFactory);
- }
- public Collection getWorkflows() {
- return hibernateTemplate.find("from Workflow");
- }
- <bean id="sessionFactory"
class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
- <property name="dataSource"><ref
local="dataSource"/></property>
- <property name="mappingResources">
- <value>mycompany/mappings.hbm.xml</value>
- </property>
- <property name="hibernateProperties">
- <props>
- <prop
key="hibernate.dialect">net.sf.hibernate.dialect.HSQLDialect</prop>
- </props>
- </property>
- </bean>
- <bean id=“myDao" class=“com.mycompany.MyHibernateDao"
- autowire="constructor"
- >
|
41
|
- Spring has it’s own exception handling hierarchy for DAO logic.
- No more copy and pasting redundant exception logic!
- Exceptions from JDBC, or a supported ORM, are wrapped up into an
appropriate, and consistent, DataAccessException and thrown.
- This allows you to decouple exceptions in your business logic. These
exceptions are treated as unchecked exceptions that you can handle in
your business tier if needed. No
need to try/catch in your DAO.
- Define your own exception translation by subclassing classes such as SQLErrorCodeSQLExceptionTranslator
|
42
|
- Easier test driven development (TDD)
- Integration testing
- Can use a standalone Spring configuration with mock objects for
testing.
- Consider XMLApplicationContext or FileSystemApplicationContext.
- Unit testing
- Allows you to test outside the container without using the Spring
container.
- Easy to test POJOs
|
43
|
- JavaMail helpers
- Scheduling support via Quartz
- Convenience implementation classes for
- Remoting support – JAXRPC, RMI, Hessian, and Burlap
- EJB support for easier access.
- Acegi Security System for Spring
- http://acegisecurity.sourceforge.net/
- Very good framework!
- Eclipse Plugin – Spring IDE for Eclipse
- Coming soon
- JMS implementation classes
- JMX support
|