Spring - PowerPoint PPT Presentation

About This Presentation
Title:

Spring

Description:

Title: Oracle 7Up Workshop - Day One - SQL Subject: Relevant new functionality from Oracle 7.x to Oracle 9i R2 Author: Lucas Jellema Keywords: sql pl/sql Oracle 9iR2 – PowerPoint PPT presentation

Number of Views:142
Avg rating:3.0/5.0
Slides: 73
Provided by: LucasJ6
Category:
Tags: load | oracle | spring | test

less

Transcript and Presenter's Notes

Title: Spring


1
Spring Power to the POJOIntroductie tot het
Spring Framework
  • Lucas Jellema
  • Oracle Consulting Java Professional
    Community,maandag 29 augustus 2005

2
Agenda
  • Introductie Spring History, Background
  • Hoe kom je aan nieuwe objecten
  • BeanFactory en Inversion of Control Dependency
    Injection
  • Hoe laat je bestaande objecten naar je pijpen
    dansen?
  • Aspect Oriented Programming (AOP)
  • Business Tier Architectuur
  • Test Driven Development
  • Spring Persistence Spring DAO
  • Spring Remoting
  • Losse eindjes, conclusies, discussie
  • Workshop

3
Where weve come from
  • EJB as we know it
  • Resembles the original JavaBeans specification in
    name only.
  • Heavyweight
  • Requires application server
  • Difficult to unit-test
  • Intrusive (must implement EJB interfaces)
  • Complex
  • Home/Remote/Local/LocalHome interfaces
  • Deployment descriptors
  • Non-intuitive

4
The future of EJB
  • Spilling the beans
  • EJB 3.0 will embrace simplicity
  • Based on POJO/POJI (? Well, maybe)
  • Employ dependency injection instead of LDAP
  • Declarative services (transactions, security)
    will be aspects
  • Entity beans will be POJOs, persisted via
    Hibernate-like framework

5
The future is NOW!
  • Spring is a lightweight container framework
  • Build applications based on POJO/POJI.
  • Wire beans together using dependency injection.
  • Declaratively apply transactions and security
    using aspect.
  • Integrates cleanly with Hibernate for
    persistence.
  • EJB 3.0Spring Hibernate Metadata

6
Spring History
  • J2EE Design and Development by Rod Johnson,
    2002
  • Introducing the i21 framework
  • First release of Spring Spring 2004
  • Spring 1.2.4 August 2005
  • Open Source
  • Interface21 small company with most core
    committers
  • Contributions from Oracle and otherparties
  • Spawned many sub-projects

7
Power to the POJO
AOP
Consistent Service Abstractions (Template Pattern)
IoC (Dependency Injection)
8
Springs modules
9
Whats more
  • Remoting support via RMI, JAX-RPC, and
    Hessian/Burlap
  • Metadata (ala, JSR-175 or Commons Attributes)
  • Persistence via TopLink, Hibernate, JDO, or
    iBatis support
  • E-mail support
  • EJB support
  • JMX Support (Spring 1.1)
  • JMS support
  • Spring Rich Client Platform (Spring 1.1)
  • Spring .Net

10
Spring is HOT!
11
Many books available
  • J2EE without EJB
  • The starting point
  • Spring Live
  • Pro Spring
  • Spring in Action
  • Professional Spring Development
  • By The Team

12
Spring Home http//www.springframework.org
13
Core SpringInversion of Control Dependency
Injection
14
Coupling
  • Highly coupled code is
  • Hard to test
  • Hard to maintain
  • Exhibits whack-a-mole style bugs
  • Here one pops up, when you solve it, another one
    appears
  • Uncoupled code is
  • Code that doesnt do anything
  • Coupling is somewhat necessary
  • but should be controlled

15
Dependency Injection
  • The Hollywood Principle Dont call me, Ill
    call you.
  • Collaborators arent asked fortheyre received.
  • Also known as Dependency Injection, thanks to
    Martin Fowler.

16
Benefits of IoC
  • Objects are more cohesive because they are no
    longer responsible for obtaining their own
    collaborators.
  • When used with interfaces, code is very loosely
    coupled.

17
Elements of a Spring app
  • Beans
  • Not EJBs. Actually, not necessarily JavaBeans.
    Just POJOs
  • Bean wiring
  • Typically an XML file.
  • A bootstrap class
  • A class with a main() method.
  • A servlet.
  • The bootstrap class uses a BeanFactory (or IoC
    Container) to retrieve POJOs
  • That have been wired and dependency injected

18
IoC Container in ActionApplication Class needs
POJOs
POJO 2
IoC Container
POJO 1
POJO 3
xml
pojo 1
pojo 2
getBean(POJO1)
pojo 3
Application
19
IoC Container in ActionApplication Class needs
POJOs
HrmServiceImpl
HrmService
IoC Container
xml
EmployeeJdbcDAO
hrmService
EmpDAO
getBean(hrmService)
employeeDao
dataSourceDBDirect
HrmClient
DriverManagerDataSource
DataSource
20
Wiring beans in XML
  • Root elements is ltbeansgt
  • Contains one or more ltbeangt elements
  • id (or name) attribute to identify bean
  • class attribute to specify class

The beans ID
ltbeansgt ltbean idfoo classcom.habuma.f
oobar.Foogt lt!-- Properties defined here --gt
lt/beangt lt/beansgt
The beans fully- qualified classname
21
Wiring a property
  • Use ltpropertygt element
  • name attribute specifies name of property

ltbeansgt ltbean idfoo classcom.habuma.f
oobar.Foogt ltproperty namebargt lt!--
Property value goes here --gt lt/propertygt
lt/beangt lt/beansgt
Maps to a setBar() call
22
Property values
  • Strings and numbers
  • Null
  • Lists and arrays

ltproperty namebargtltvaluegt42lt/valuegtlt/propertygt
ltproperty namebargtltvaluegtHellolt/valuegtlt/propert
ygt
ltproperty namebargtltnull/gtlt/propertygt
ltproperty namebargt ltlistgt
ltvaluegtABClt/valuegt ltvaluegt123lt/valuegt
lt/listgt lt/propertygt
23
Property values
  • Sets
  • Maps

ltproperty namebargt ltsetgt
ltvaluegtABClt/valuegt ltvaluegt123lt/valuegt
lt/setgt lt/propertygt
ltproperty namebargt ltmapgt ltentry
keykey1gtltvaluegtABClt/valuegtlt/entrygt ltentry
keykey2gtltvaluegt123lt/valuegtlt/entrygt
lt/setgt lt/propertygt
24
Property values
  • Property sets
  • Other beans

ltproperty namebargt ltpropsgt ltprop
keyprop1gtABClt/propgt ltprop
keyprop2gt123lt/propgt lt/setgt lt/propertygt
ltproperty namebargt ltref beanbar/gt lt/proper
tygt
25
Auto-wiring
  • You can auto-wire
  • byName Property names are matched to bean
    names
  • byType Property names are matched to bean
    types
  • constructor Pico-like constructor wiring. Like
    byType except using constructor.
  • autodetect Uses reflection to decide whether
    to use byType or constructor

26
Auto-wiring
ltbean idfoo classcom.habuma.foobar.Foo
autowirebyName/gt
ltbean idfoo classcom.habuma.foobar.Foo
autowirebyNamegt ltproperty
namebargtltvaluegtbarlt/valuegtlt/propertygt lt/beangt
ltbeans default-autowirebyTypegt lt!-- Bean
definitions go here --gt lt/beansgt
27
BeanFactory vs. ApplicationContext
  • A BeanFactory is the Spring container.
  • Loads beans and wires beans together.
  • Dispenses beans as requested.
  • XmlBeanFactory is the most commonly used.
  • An ApplicationContext is a BeanFactory, but adds
    framework features such as
  • I18N messages
  • Event notification

28
IoC Examples
29
Example of a IoC based programming
30
The knight before
31
The knight after
32
Core SpringAspect Oriented Programming
  • AOP a programming technique that promotes
    separation of concerns within a software system
  • Recurring often infrastructural concerns can
    easily be duplicatedin many objects
  • Security
  • Transaction Management
  • Logging
  • Profiling
  • AOP suggestsseparation
  • Concerns are appliedat compile or run-time

33
AOP in a nutshell
  • Aspect A modularization of a cross-cutting
    concern. Implemented in Spring as Advisors or
    interceptors
  • Joinpoint Point during the execution of
    execution.
  • Advice Action taken at a particular joinpoint.
  • Pointcut A set of joinpoints specifying where
    advice should be applied.
  • Advisor Fully represents an aspect, including
    both advice and a pointcut.
  • Introduction Adding methods or fields to an
    advised class.
  • Weaving Assembling aspects into advised objects.

34
Without AOP
35
With AOP
36
Implementing AOP
  • Compile time modify the source code during
    compilation
  • Requires a customized Java Compiler
  • For example AspectJ Spring does not do compile
    time AOP
  • Run time byte injection
  • Change the class when loaded, generating a
    subclass that contains the aspects
  • Uses CGLib library
  • Run time using the JDK 1.3 Dynamic Proxy
  • Instead of getting an object instance, the
    application receives a proxy object
  • The proxy implements the same interface
  • And maybe something else as well
  • Besides, it can intercept and wrap method calls

37
IoC Container hides AOP implementation from POJO
consumer
Aspect A invoke()
Proxy
Pojo1Impl
xml
target
Aspect B before()
targetpojo1Impl
IoC Container
implements
  • pojo1 proxy
  • Target
  • interceptorNames
  • gt AspectA, AspectB

implements
POJO 1(interface)
getBean(POJO1)
Application
AspectA
AspectB
38
Different types of Advice
  • Before advice
  • Calls to advised methods are intercepted before
    the method is called.
  • After returning advice
  • Calls to advised methods are intercepted after a
    successful return.
  • After throws advice
  • Calls to advised methods are intercepted after an
    exception is thrown.
  • Around advice/interception
  • Calls to advised methods are intercepted. Call
    must be explicitly made to target method.
  • Introduction advice
  • Allows a class (or rather its proxy) to implement
    additional interfaces
  • Calls to methods are interceptedeven when the
    target bean doesnt have the method!
  • Actually, just a special case of around advice

39
Creating Advise
  • Create a class that implements one or more of the
    Spring AOP interfaces
  • MethodInterceptor
  • BeforeAdvice
  • AfterReturningAdvice
  • ThrowsAdvice
  • Implement the interface method
  • before (Method method, Object args)
  • afterReturning(Object returnValue, Method method,
    Object args)
  • invoke(MethodInvocation invocation)

40
Defining Pointcuts in Spring(specify where to
apply which Advice)
  • Programmatically
  • No BeanFactory required
  • Can be used independently of the rest of Spring
  • Declaratively
  • In the bean container configuration file
    (applicationContext.xml)

41
Applications of AOP by Spring itselfalways in
conjunction with IoC/DI
  • Remoting Support
  • Proxy references a remote object
  • Transaction Management
  • Service method is wrapped in around advice that
    opens and closes the transaction
  • Security
  • JMX
  • Proxy implements the MBean interfaces for its
    target object
  • Mock Testing
  • Tested objects are injected with Mock objects
    that are dynamically created (made up)

42
AOP with HotSwap Demo
EmployeeImpl
target
Employee
Proxy
Employee
Client
EmployeeImpl
Employee
target
target
Employee
HotSwappableTargetSource
Proxy
43
AOP with HotSwap Demo
EmployeeImpl
Employee
John Doe
emp
Client
EmployeeImpl
scott
target
target
alsoscott
Employee
HotSwappableTargetSource
Proxy
John Smith
Validator Interceptor
EmployeeValidator
SAL Salesmenlt 4000
44
After HotSwap on scott
EmployeeImpl
setSal(2500)
Employee
John Doe
emp
Client
target
EmployeeImpl
scott
getSal()
target
alsoscott
Employee
HotSwappableTargetSource
Proxy
John Smith
Validator Interceptor
EmployeeValidator
SAL Salesmenlt 4000
45
Future of AOP according to Rod Johnson
  • Programming Aspects and composing an Application
    from Aspects will become widely accepted
  • Various orthogonal concerns can be dealt with in
    parallel
  • Maintaining a single cross application concern
    is done by maintaining a single aspect
  • Tool and Runtime support for AOP will further
    increase
  • Development of IBM WebSphere WSAD is heavily
    done in an AOP fashion

46
Springs recommended Application Guidelines and
Architecture
  • Program against interfaces
  • For example Service Interface, DAO Interfaces
  • Typically no interfaces for Domain Classes
  • No configuration plumbing in your classes
  • Have configuration details injected
  • Domain Classes are used through all tiers
  • No Struts ActionForms to wrap domain classes
  • Controllers use Business Service methods to
    create or manipulate Domain Objects
  • Practice Test driven development

47
Springs recommended architecture
Presentation Tier
View Components Generate HTML or PDF
Remote Service Exporters Using SOAP, RMI, JAX-RPC
etc.
Web Tier Actions (Controllers)
Business Tier
Business Services Layer Interfaces and Container
Managed Implementations
Data Tier
DAO Interface Layer Interfaces, independent of
implementing DAO Technology
Persistent DomainObjects
DAO Implementation layer Retrieves, saves
entities using ORM tool or JDBC
O/R Mapping Layer
JDBC
JDBC
RDBMS
48
Spring and Test Driven Development
  • Agile Software Engineering methods, such as XP
  • First design and develop a test based on
    interfaces
  • Before implementing the interfaces
  • Before starting to resolve a bug
  • Automated Unit Testing for every class in the
    application
  • At every stage of development, the test can be
    rerun!
  • Unit Testing usually based on JUnit
  • Great integration in Eclipse and JDeveloper
    10.1.3 (10.1.2 is somewhat sparse)

49
Spring and Test Driven Development
  • Challenges include
  • Container Dependencies (HttpServlet object)
  • Dependencies on external objects (not a unit
    test)
  • Especially objects that are hard to configure,
    e.g. DAO Impl
  • Dependencies on objects that have not yet been
    implemented

50
Spring support for Test Driven Development
  • When all objects (Service and DAO Impl) are
    Spring Beans
  • They get dependency injected by the container
  • During a test, instead of injecting them with
    real objects
  • We can inject them with Mock Objects, that will
    return the values we specify when called
  • The real objects do not need to exist
  • even when they do exist, using mock objects
    ensures we are performing a true UNIT test

51
Unit Testing HrmServiceImpl using Mock objects
Unit Test
MockEmployeeDAOImpl
HrmServiceTest (JUnit TestCase)
Business Tier
HrmServiceImpl
Data Tier
EmployeeDAO Interfaces, independent of
implementing DAO Technology
Persistent DomainObjects
EmployeeDAOImpl (does not yet exist)
52
Testen en MockObjects
  • public class TestEmployeeDao
  • extends AbstractDependencyInjectionSpringC
    ontextTests
  • private EmployeeDao employeeDAO
  • public void setEmployeeDAO(EmployeeDao
    employeeDAO)
  • this.employeeDAO employeeDAO
  • protected String getConfigLocations()
  • return new String
  • "nl/amis/demo/dao/jdbc/applicationCon
    text-jdbc.xml"
  • public void testFindEmployeeById ()
  • Employee emp employeeDAO.getEmployeeById
    (7839)
  • assertEquals("KING", emp.getName())

ltbean id"employee7839" class"nl.amis.demo.domain
.Employee"gt ltproperty name"name"
value"KING" /gt ltproperty name"employeeNumber
" value"7839" /gt ltproperty name"job"
value"PRESIDENT" /gt lt/beangt ltbean
id"employeeMockDAO" class"nl.amis.demo.dao.Emplo
yeeMockDao"gt ltproperty name"emp"gt
ltref local"employee7839" /gt
lt/propertygt lt/beangt
53
Spring JDBC and Spring DAO
Properly implementing those Mock DAO objects
54
Doelen van Spring JDBC
  • Database acties
  • SQL (Select en Manipulatie)
  • Procedural (stored procedure calls)
  • Flexibel
  • Externe configuratie van data source
  • Geen Checked Exceptions
  • Out of container testen
  • Database onafhankelijk
  • Gecontroleerd
  • Exception handling
  • Connection leaking/connection pooling
  • Productief
  • Geen herhaling van code (tcftc)
  • Vereenvoudigen van Transaction Management

55
Architectuur
Domain Object
Domain Object
Domain Object
JNDI
Service
DAO
56
Example
  • import java.sql.
  • import javax.sql.
  • public class EmpDao
  • public List getAllEmployees()
  • Connection con null
  • PreparedStatement pstmt null
  • ResultSet rs null
  • List emps new ArrayList()
  • try
  • con getConnection()
  • pstmt con.prepareStatement
  • ("select from emp")
  • rs pstmt.executeQuery()
  • while (rs.next())
  • Employee e new Employee()
  • e.setId (rs.getLong(1))
  • e.setName (rs.getString(2))
  • // ...
  • emps.add(e)

private Connection getConnection() throws
SQLException try
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver())
return DriverManager.getConnection
("jdbcoraclethin_at_localhost1521orcl
,"scott", "tiger") catch (SQLException
sqle) // handle exception
return null
private Connection getConnection() throws
SQLException try Context ic
new InitialContext() DataSource
ds (DataSource) ic.lookup
("javacomp/env/jdbc/myDatabase")
return ds.getConnection() catch
(NamingException e) // handle
exception return null
57
Template Pattern
  • Operation largely follows a standard algorithm
  • At certain steps, specialization or customization
    is required
  • Several implementations
  • Abstract hook methods that sub-class may
    override
  • Parametrize behaviour and have invoker provide
    the details
  • Such as the SQL Query
  • Spring JDBC Templates
  • Implement all JDBC wiring
  • Parametrize the query and the result-handling

58
Example of Spring JDBC Template
  • public interface empDao
  • public List getAllEmployees ()

public class EmployeeJdbcDao extends
JdbcDaoSupport implements EmpDao public
List getAllEmployees() JdbcTemplate jt
getJdbcTemplate() return
jt.queryForList (select from emp)
ltbean id"dataSourceDBDirect"
class"org.springframework.jdbc.datasource.DriverM
anagerDataSource" destroy-method"close"gt
ltproperty name"driverClassName"
value"oracle.jdbc.driver.OracleDriver" /gt
ltproperty name"url" value"jdbcoraclethin_at_loca
lhost1521BAARSJES1" /gt ltproperty
name"username" value"scott" /gt ltproperty
name"password" value"tiger" /gt lt/beangt ltbean
id"employeeDAO" class"nl.amis.demo.dao.jdbc.Empl
oyeeJdbcDao" gt ltproperty name"dataSource"gt
ltref local"dataSourceDBDirect" /gt
lt/propertygt lt/beangt
59
jdbc helper classes
  • JdbcTemplate
  • query, queryForList, queryForInt, queryFor..
  • ArrayList (per row) of HashMaps (column name as
    key)
  • RowMapper
  • PreparedStatementCreator/Callback
  • MappingSQLQuery
  • ...

60
How can Spring help?
  • Make life easier
  • DAO Support
  • JDBC, Hibernate, Toplink, iBatis, JDO,
    javax.persistence (EJB 3.0) , ...
  • Dependency Injection
  • Jdbc helper classes
  • Exception Handling
  • MockObjects
  • Transaction Management

61
Spring Architectuur
Domain Object
Domain Object
JdbcDaoSupport HibernateDaoSupport TopLinkDaoSuppo
rt ...
XXDAO Support
DAO Interface
Domain Object
Service
DAO
ApplicationContext-jdbc
62
Exception Handling
  • RuntimeException ipv checked SQLException
  • DataAccessException
  • SQLException Translation
  • DataIntegrityViolationException
  • DataRetrievalFailureException
  • CannotGetJdbcConnectionException
  • ...

63
Spring and Web ApplicationsStruts and other
Controller Frameworks
  • Struts support
  • Auto-Load WebContext ( BeanFactory) in session
  • Make Action Classes Spring aware and have them
    reference the WebContext
  • Proxy Action Classes and Dependency Inject them
  • Register Actions as Spring Beans
  • Similar support for
  • WebWork
  • Tapestry

64
Spring and Web ApplicationsJava Server Faces
  • Java Server Faces
  • JSF has managed-beans
  • Very similar to Spring Beans
  • Though no support for AOP
  • And do you want low level, persistency related
    configuration details in the faces-config.xml
  • JSF-Spring project offers a JSF variable resolver
  • It takes bean references in faces-config.xml and
    tries to resolve them in Spring context files

65
Spring and Web ApplicationsSpring MVC Controller
Framework
  • Positioned to replace Struts
  • Better, more intuitive, modern architecture
  • Full benefits from IoC and AOP
  • Works with (these are all Spring Beans)
  • Controllers that process the request, update
    and prepare the Model they also return a result,
    a symbolic indication of the ModelView to proceed
    to
  • ViewResolvers that decide which View to let
    render
  • ViewBeans thatwrap View Componentssuch as
    JSP, Velocity Template, FreeMarker page

66
Spring MVC Controller FrameworkSupport for
various View technologies
  • JSP using the Spring tag-library (very small,
    primarily use JSTL)
  • FreeMarker
  • Velocity
  • Tiles
  • File Download
  • Excel using Apache POI
  • PDF using iText
  • XSL-T
  • JasperReports

67
Spring RemoteSupport for distributed applications
  • Springs number one concept concerning remote,
    distributed objects (take from Martin Fowler)
  • Do NOT distribute!!!
  • However, in certain circumstances you probably
    have to
  • Cross organizational boundaries
  • Rich Clients
  • Remote process accessing back-end server

68
Springs Remote Façade Philosphy
  • Remote access
  • for example supporting remote clients over RMI or
    publishing a WebService
  • should be regarded as an alternative presentation
    layer
  • no different from an standard Browser oriented
    HTML interface
  • On well-defined middle tier service interfaces
  • that are blissfully unaware that they are exposed
    and consumed remotely
  • Remoting infrastructure for example Data
    Transfer Objects should be added on top of the
    well defined, OO, fully POJO based service

69
Spring support for remoting
  • Spring will
  • Declaratively expose Service interfaces for
    remote clients
  • Declaratively expose remote Service interfaces
    for local clients
  • Support for these protocols
  • RMI
  • Cauchos Hessian and Burlap
  • Springs own HttpInvoker
  • EJB
  • SOAP (based on JAX-RPC, using AXIS or XFire)

70
Exposing Service to remote clients
ClientCode
Proxy for Service (generated by BeanFactory)
Service Interface
Spring Exporter
Service Implementation
71
Spring Exporters
  • Declaratively set up in the configuration file
  • Using a specific protocol
  • Spring Service Exporter
  • defines an End Point where the Service can be
    invoked
  • typically linked to a port
  • translates incoming remote calls to local calls
  • unmarshalling parameter values
  • marshalling return values and exceptions
  • Spring Exporter often works with Spring Remote
    Client

72
Details from Server and Client side
BeanConfiguration files
  • Server Side HttpInvoker Protocol Exporter
  • Client Side HttpInvoker Protocol proxy creator

73
Extra Features
  • JMX proxy Spring Beans to register them as
    MBeans
  • JMS
  • Email
  • JNDI
  • Scheduling (Quartz)
  • Transaction Management

74
Spring and the Oracle Java Technology Stack
  • Spring DAO has TopLink support
  • Since Spring 2005, contributed by Oracle
  • Spring based POJO business service can be
    registered with ADF Binding Framework
  • Ideally we can have the registration mechanism
    honor the ApplicationContext origin of the
    Service Object
  • Question how does ADF currently instantiate its
    Business Services?
  • Spring DAO for ADF BC seems pointless
  • ADF BC is already pretty much wrapped the API
    is already fairly high level
  • The Configurations (bc4j.xcfg) provide a level of
    decoupling and dependency injection
  • Spring DAO focuses on POJO ADF BC does not

75
Spring and the Oracle Java Technology Stack
  • Spring MVC on ADF BC Business Service could be
    done
  • though a lot of the natural benefits are lost
  • UIX could be used with Spring MVC as View
    technology
  • losing the Struts ADF LifeCyle management
  • Shortly ADF Faces can be used with Spring MVC as
    well
  • Spring Remoting can be used to publish and
    consume
  • Somewhat overlapping with JDeveloper WebServices
    support
  • Spring AOP could be applied to ADF BC objects
  • If we can find the right hook does not seem
    easy!

76
Sub Projects and initiatives around Spring
  • Spring Security
  • Spring IDE (for Eclipse)
  • Spring Rich Client
  • Spring Modules Spring WebFlow
  • Spring BeanDoc
  • Spring .NET by Rod Johnson et. al.
  • Focus on C
  • JSF-Spring
  • XDoclet Spring Bean Configuration generator
  • Aurora MVC Framework
  • More support for Persistency OO/R Frameworks
  • EJB 3.0

77
Discussion
Ik lust eigenlijk nu ook wel een kop koffie
Write a Comment
User Comments (0)
About PowerShow.com