Spring - PowerPoint PPT Presentation

1 / 54
About This Presentation
Title:

Spring

Description:

Spring Spring Overview Spring Container Concepts Spring and AOP Spring and Data Access Managing Transactions and Resources Remoting and Accessing Enterprise Services ... – PowerPoint PPT presentation

Number of Views:48
Avg rating:3.0/5.0
Slides: 55
Provided by: sravisank
Category:
Tags: spring

less

Transcript and Presenter's Notes

Title: Spring


1
Spring
2
  • Spring Overview
  • Spring Container Concepts
  • Spring and AOP
  • Spring and Data Access
  • Managing Transactions and Resources
  • Remoting and Accessing Enterprise Services
  • Spring Web Framework
  • Integrating with Struts
  • DAO and LDAP support

3
Spring Overview
  • Spring is a Lightweight Application Framework
  • Spring Promotes loose coupling through Inversion
    of Control (IoC)
  • Spring comes with rich support for
  • Aspect-Oriented Programming.

4
Spring Overview
  • Lightweight Container
  • Very loosely coupled
  • Components widely reusable and separately
    packaged
  • Created by Rod Johnson
  • Based on Expert one-on-one J2EE Design and
    Development
  • Currently on version 1.1.1

5
Why Use Spring?
  • Wiring of components (Dependency Injection)
  • Promotes/simplifies decoupling, design to
    interfaces
  • Declarative programming without J2EE
  • Easily configured aspects, esp. transaction
    support

6
Why Use Spring?
  • Conversion of checked exceptions to unchecked
  • (Or is this a reason not to use it?)
  • Not an all-or-nothing solution
  • Extremely modular and flexible
  • Well designed
  • Easy to extend
  • Many reusable classes

7
Architectural benefits
  • Spring can effectively organize your middle tier
    objects, whether or not you choose to use EJB.
  • Spring's configuration management services can be
    used in any architectural layer, in whatever
    runtime environment.
  • Spring can use AOP to deliver declarative
    transaction management without using an EJB
    container.

8
Architectural benefits
  • Spring provides a consistent framework for data
    access, whether using JDBC or an O/R mapping
    product such as TopLink, Hibernate
  • Spring provides a consistent, simple programming
    model in many areas JDBC, JMS, JavaMail, JNDI and
    many other important APIs.

9
Spring Framework
  • The Spring framework is a layered architecture
    consisting of seven well-defined modules. The
    Spring modules are built on top of the core
    container, which defines how beans are created,
    configured and managed.

10
Spring Framework
11
Spring Framework
  • Core container
  • Provides the essential functionality of the
    Spring
  • framework.
  • Primary component of the core container is the
  • BeanFactory, an implementation of the Factory
  • pattern.
  • BeanFactory applies the Inversion of Control
    (IOC)
  • pattern to separate an application's
    configuration and
  • dependency specification from the actual
    application code.

12
Spring Framework
  • Spring context
  • Spring context is a configuration file that
    provides context information to the Spring
    framework. The Spring context includes enterprise
    services such as JNDI, EJB, e-mail, validation,
    and scheduling functionality.

13
Spring Framework
  • Spring AOP
  • The Spring AOP integrates aspect-oriented
    functionality directly into the Spring framework.
  • Provides transaction management services for
    objects in any Spring-based application.
  • Incorporates declarative transaction
    management capabilities into applications without
    relying on EJB components.

14
Spring Framework
  • Spring DAO
  • Spring JDBC DAO abstraction layer offers
    exception hierarchy for managing the exception
    handling and error messages thrown by different
    database vendors.
  • The exception hierarchy simplifies error handling
    and greatly reduces the amount of exception code
    you need to write, such as opening and closing
    connections.
  • Spring DAO's JDBC-oriented exceptions comply to
    its generic DAO exception hierarchy.

15
Spring Framework
  • Spring ORM
  • The Spring framework plugs into several ORM
    frameworks to provide its Object Relational tool,
    including JDO and Hibernate.
  • All of these comply to Spring's generic
    transaction and DAO exception hierarchies.

16
Spring Framework
  • Spring Web module
  • The Web context module builds on top of the
    application context module, providing contexts
    for Web-based applications.
  • The Web module also eases the tasks of
    handling multi-part requests and binding request
    parameters to domain objects.

17
  • Spring MVC framework
  • The Model-View-Controller (MVC) framework
    featured MVC implementation for building Web
    applications.
  • The MVC framework is highly configurable via
    strategy interfaces and accommodates numerous
    view technologies including JSP, Velocity, Tiles
    and iText.

18
Aspect Oriented Programming
  • Aspect-oriented programming, or AOP, is a
    programming technique that allows programmers to
    modularize crosscutting concerns, or behavior
    that cuts across the typical divisions of
    responsibility, such as logging and transaction
    management.

19
BeanFactory Usage
InputStream is new FileInputStream("beans.xml")
XmlBeanFactory factory new XmlBeanFactory(is)
MyBeanClass bean (MyBeanClass)factory.getBean(
myBean)
OR
ApplicationContext ctx new ClassPathXmlApplicati
onContext("beans.xml") MyBeanClass bean
(MyBeanClass)ctx.getBean(myBean)
20
Spring Dependency Injection
  • Inversion of Control (IoC)
  • Hollywood Principle
  • Don't call me, I'll call you
  • Container resolves (injects) dependencies of
    components by setting implementation object
    (push)
  • As opposed to component instantiating or Service
    Locator pattern where component locates
    implementation (pull)
  • Martin Fowler calls Dependency Injection

21
Dependency Injection (cont'd)
  • BeanFactory configured components need have no
    Spring dependencies
  • Simple JavaBeans
  • Beans are singletons by default
  • Properties may be simple values or references to
    other beans
  • Built-in support for defining Lists, Maps, Sets,
    and Properties collection types.

22
XmlBeanFactory Example
  • Property and constructor based IoC

ltbean id"exampleBean" class"examples.ExampleBean
"gt ltproperty name"beanOne"gtltref
bean"anotherExampleBean"/gtlt/propertygt
ltproperty name"beanTwo"gtltref bean"yetAnotherBean
"/gtlt/propertygt ltproperty name"integerProperty
"gt1lt/propertygt lt/beangt ltbean id"anotherExampleBe
an" class"examples.AnotherBean"/gt ltbean
id"yetAnotherBean" class"examples.YetAnotherBean
"/gt
ltbean id"exampleBean" class"examples.ExampleBean
"gt ltconstructor-arggtltref bean"anotherExampleB
ean"/gtlt/constructor-arggt ltconstructor-arggtltref
bean"yetAnotherBean"/gtlt/constructor-arggt
ltconstructor-arggtltvaluegt1lt/valuegtlt/constructor-arg
gt lt/beangt ltbean id"anotherExampleBean"
class"examples.AnotherBean"/gt ltbean
id"yetAnotherBean" class"examples.YetAnotherBean
"/gt
23
Bean Creation
  • Direct instantiation
  • ltbean idbeanId classclassNamegt
  • BeanFactory instantiation
  • Same syntax but class is subclass of BeanFactory
  • getObject() called to obtain Bean
  • Static Factory
  • ltbean idbeanId classclassName"
    factory-method" staticCreationMethodgt
  • Instance Factory Method
  • ltbean idbeanId factory-beanexistingBeanId"
    factory-methodnonStaticCreationMethod"gt

24
Autowiring Properties
  • Beans may be auto-wired (rather than using ltrefgt)
  • Per-bean attribute autowire
  • Explicit settings override
  • autowirename
  • Bean identifier matches property name
  • autowiretype
  • Type matches other defined bean
  • autowireconstructor
  • Match constructor argument types
  • autowireautodetect
  • Attempt by constructor, otherwise type

25
Web Initialization
  • Web applications may use ContextLoaderListener to
    initialize Spring

web.xml
ltcontext-paramgt ltparam-namegtcontextConfigLocat
ionlt/param-namegt ltparam-valuegt/WEB-INF/daoConte
xt.xml /WEB-INF/applicationContext.xml
lt/param-valuegt lt/context-paramgt ltlistenergt
ltlistener-classgtorg.springframework.web.context.C
ontextLoaderListenerlt/listener-classgt
lt/listenergt
Automatically done by Spring DispatcherServlet
26
ApplicationContext Example
ltbean id"propertyConfigurer"
class"org.springframework.beans.factory.config.Pr
opertyPlaceholderConfigurer"gt ltproperty
name"location"gtltvaluegtdatabase.propertieslt/valuegt
lt/propertygt lt/beangt ltbean
id"dataSource" class"org.springframework
.jdbc.datasource.DriverManagerDataSource"gt
ltproperty name"driverClassName"gt
ltvaluegtdatabase.connection.driver_classlt/valuegt
lt/propertygt ltproperty
name"url"gt ltvaluegtdatabase.connecti
on.urllt/valuegt lt/propertygt lt/beangt
27
Spring AOP
28
AOP Fundamentals
  • Aspect-oriented programming (AOP) provides for
    simplified application of cross-cutting concerns
  • Transaction management
  • Security
  • Logging
  • Auditing
  • Locking

29
Transactions
30
AOP Transactions
  • Spring provides AOP support for declarative
    transactions
  • Delegates to a PlatformTransactionManager
    instance
  • DataSourceTransactionManager
  • HibernateTransactionManager
  • JdoTransactionManager
  • JtaTransactionManager

31
Transaction Configuration
ltbean id"sessionFactory" class"org.springfra
mework.orm.hibernate.LocalSessionFactoryBean"gt
ltproperty name"dataSource"gtltref
bean"dataSource"/gtlt/propertygt ltproperty
name"mappingResources"gt ltlistgt
ltvaluegtcom/../model/.hbm.xmllt/valuegt
lt/listgt lt/propertygt lt/beangt ltb
ean id"transactionManager class"org.springfram
ework.orm.hibernate.HibernateTransactionManager"gt
ltproperty name"sessionFactory"gt ltref
bean"sessionFactory"/gt lt/propertygt lt/beangt
32
Declarative Transactions
  • Declarative transactional support can be added to
    any bean by using TransactionProxyFactoryBean
  • Similar to EJB, transaction attributes may be
    defined on a per-method basis

33
Injecting Transaction Support
Declarative transaction support for single bean
ltbean idreservationService"
class"org.springframework.transaction.interceptor
.TransactionProxyFactoryBean"gt ltproperty
name"transactionManager"gt ltref
bean"transactionManager"/gt lt/propertygt
ltproperty name"target"gtltref localreservationSer
viceTarget"/gtlt/propertygt ltproperty
name"transactionAttributes"gt ltpropsgt
ltprop keyreserveRoom"gtPROPAGATION_REQUIRED
lt/propgt ltprop key""gtPROPAGATION_REQUIR
ED,readOnlylt/propgt lt/propsgt
lt/propertygt lt/beangt
34
Transaction Autoproxy
ltbean id"autoproxy" class"org...DefaultAdvi
sorAutoProxyCreator"gt lt/beangt ltbean
id"transactionAdvisor" class"org...Transacti
onAttributeSourceAdvisor" autowire"constructo
r" gt lt/beangt ltbean id"transactionInterceptor"
class"org...TransactionInterceptor"
autowire"byType"gt lt/beangt ltbean
id"transactionAttributeSource"
class"org...AttributesTransactionAttributeSource"
autowire"constructor"gt lt/beangt ltbean
id"attributes" class"org...CommonsAttributes
" /gt
Generic autoproxy support
Invokes interceptor based on attributes
Applies transaction using transactionManager
Caches metadata from classes
35
Data Access
36
Data Access
  • DAO support provides pluggable framework for
    persistence
  • Currently supports JDBC, Hibernate, JDO, and
    iBatis
  • Defines consistent exception hierarchy (based on
    RuntimeException)
  • Provides abstract Support classes for each
    technology
  • Template methods define specific queries

37
DAO Support
  • The Data Access Object (DAO) support in Spring
    is primarily aimed at making it easy to work with
    data access technologies like JDBC, Hibernate or
    JDO in a standardized way.

38
DAO Support
  • ltbean id"dataSource" class"org.springframework.
    jndi.JndiObjectFactoryBean" lazy-init"default"
    autowire"default" dependency-check"default"gt
  • ltproperty name"jndiName"gt
  • ltvaluegtcom.bt.bbv.r1osslt/valuegt
  • lt/propertygt
  • lt/beangt
  • ltbean id"jdbcTemplate" class"org.springframewor
    k.jdbc.core.JdbcTemplate" lazy-init"default"
    autowire"default" dependency-check"default"gt
  • ltproperty name"dataSource"gt
  • ltref bean"dataSource" /gt
  • lt/propertygt
  • lt/beangt
  • lt/beansgt

39
Hibernate DAO Example
public class ReservationDaoImpl extends
HibernateDaoSupport implements
ReservationDao public Reservation
getReservation (Long orderId) return
(Reservation)getHibernateTemplate().load(Reservati
on .class,

orderId) public void
saveReservation (Reservation r)
getHibernateTemplate().saveOrUpdate(r)
public void remove(Reservation
Reservation) getHibernateTemplate().del
ete(r)
40
Hibernate DAO (contd)
public Reservation findReservations(Room
room) List list getHibernateTemplate().f
ind( "from Reservation reservation
where reservation.resource ?
order by reservation.start",
instrument) return (Reservation)
list.toArray(new Reservationlist.size())
41
Hibernate DAO (contd)
public Reservation findReservations(final
DateRange range) final HibernateTemplate
template getHibernateTemplate() List list
(List) template.execute(new HibernateCallback()
public Object doInHibernate(Session
session) Query query
session.createQuery( "from
Reservation r where r.start
gt rangeStart and r.start lt rangeEnd )
query.setDate("rangeStart", range.getStartDate()
query.setDate("rangeEnd",
range.getEndDate()) return
query.list() ) return
(Reservation) list.toArray(new
Reservationlist.size())
42
Hibernate Example
ltbean id"sessionFactory" class"org.springframewo
rk.orm.hibernate.LocalSessionFactoryBean"gt
ltproperty name"dataSource"gtltref
bean"dataSource"/gtlt/propertygt ltproperty
name"mappingResources"gt ltlistgt
ltvaluegtcom/jensenp/Reservation/Room.hbm.xmllt/value
gt ltvaluegtcom/jensenp/Reservation/Reservati
on.hbm.xmllt/valuegt ltvaluegtcom/jensenp/Rese
rvation/Resource.hbm.xmllt/valuegt lt/listgt
lt/propertygt ltproperty name"hibernatePrope
rties"gt ltpropsgt ltprop
key"hibernate.dialect"gthibernate.dialectlt/prop
gt ltprop key"hibernate.hbm2ddl.auto"gthib
ernate.hbm2ddl.auto lt/propgt
ltprop key"hibernate.show_sql"gthibernate.show_sq
llt/propgt lt/propsgt lt/propertygt
lt/beangt ltbean idreservationDao"
class"com.jensenp.Reservation.ReservationDaoImpl"
gt ltproperty name"sessionFactory"gtltref
bean"sessionFactory"/gt lt/propertygt lt/beangt
43
JDBC Support
  • JDBCTemplate provides
  • Translation of SQLExceptions to more meaningful
    Spring Runtime exceptions
  • Integrates thread-specific transactions
  • MappingSQLQuery simplifies mapping of ResultSets
    to Java objects

44
Web Framework
45
DispatcherServlet
  • The DispatcherServlet is the Spring Front
    Controller
  • Initializes WebApplicationContext
  • Uses /WEB-INF/servlet-name-servlet.xml by
    default
  • WebApplicationContext is bound into
    ServletContext

46
DispatcherServlet Configuration
  • HandlerMapping
  • Routing of requests to handlers
  • HandlerAdapter
  • Adapts to handler interface. Default utilizes
    Controllers
  • HandlerExceptionResolver
  • Maps exceptions to error pages
  • Similar to standard Servlet, but more flexible
  • ViewResolver
  • Maps symbolic name to view

47
Dispatcher Servlet Configuration
  • MultipartResolver
  • Handling of file upload
  • LocaleResolver
  • Default uses HTTP accept header, cookie, or
    session

48
Controllers
  • Controller interface defines one method
  • ModelAndView handleRequest(HttpServletRequest
    req, HttpServletResponse resp) throws Exception
  • ModelAndView consists of a view identifier and a
    Map of model data

49
Controller Implementations
  • CommandControllers bind parameters to data
    objects
  • AbstractCommandController
  • AbstractFormController
  • SimpleFormController
  • WizardFormController

50
Integration with Struts
  • ltplug-in className"org.springframework.web.struts
    .ContextLoaderPlugIn"gt  ltset-property
    property"contextConfigLocation"
    value"/WEB-INF/spring/core/spring-advice.xml,/WEB
    -INF/spring/core/spring-dao.xml,/WEB-INF/spring/co
    re/spring-email.xml,/WEB-INF/spring/core/spring-se
    rvices.xml,/WEB-INF/spring/core/spring-tasks.xml,/
    WEB-INF/spring/core/spring-webservices.xml" /gt
  • lt/plug-ingt

51
Integration with Struts
  • ltbean id"CispWebService" class"com.bt.bbv.core.u
    til.webservices.WebServiceProxyFactoryBean"gt
  • lt/propertygt- ltproperty name"servicePrefix"gt
  •   ltvaluegtCISPlt/valuegt  
  • lt/propertygt ltproperty name"wsdlDocumentUrl"gt 
  • ltvaluegtclasspathcom/btexact/cisp/api/CispApiEJB.
    wsdllt/valuegt
  • lt/propertygt- ltproperty name"serviceInterface"gt
    ltvaluegtcom.bt.bbv.core.service.cisp.webservice.Cis
    pApiEJBPortlt/valuegt
  • ltproperty name"serviceName"gtltvaluegtCispApiEJBlt/va
    luegt
  • lt/propertygt ltproperty name"portName"gt 
    ltvaluegtCispApiEJBPortlt/valuegt
  • lt/propertygt ltproperty name"portInterface"gtltval
    uegtcom.btexact.cisp.api.CispApiEJBPortlt/valuegtlt/pr
    opertygt
  • lt/beangt

52
Integration with LDAP
  • ltpublic class TraditionalPersonDaoImpl implements
    PersonDao
  • public List getAllPersonNames()
  • Hashtable env new Hashtable()
  • env.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.ldap.LdapCtxFactory")
  • env.put(Context.PROVIDER_URL,
    "ldap//localhost389/dcexample,dccom")
  • DirContext ctx new InitialDirContext(env)
  • catch (NamingException e)
  • throw new RuntimeException(e)

53
Integration with EJB
  • ltbean id"myComponent class"org.springframework.
    ejb.access.LocalStatelessSessionProxyFactoryBean"gt
  • ltproperty name"jndiName" value"ejb/myBean"/gt
    ltproperty name"businessInterface"
    value"com.mycom.MyComponent"/gt lt/beangt

54
References
  • Springs homepage http//www.springframework.org
  • Introducing the Spring Framework by Rod
    Johnson http//theserverside.com/news/thread.jsp?
    thread_id21893
  • Inversion of control containers and dependency
    injection by Martin Fowler http//www.martinfowl
    er.com/articles/injection.html
  • AOP Alliance http//aopalliance.sourceforge.net
Write a Comment
User Comments (0)
About PowerShow.com