Spring Talk 111204

download Spring Talk 111204

of 57

Transcript of Spring Talk 111204

  • 8/8/2019 Spring Talk 111204

    1/57

    Spring

    Paul Jensen

    Principal, Object Computing Inc.

  • 8/8/2019 Spring Talk 111204

    2/57

    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 andDevelopment

    Currently on version 1.1.1

  • 8/8/2019 Spring Talk 111204

    3/57

    Why Use Spring? Wiring of components (Dependency Injection)

    Promotes/simplifies decoupling, design to interfaces, TDD

    Declarative programming without J2EE

    Easily configured aspects, esp. transaction support

    Simplify use of popular technologies

    Abstractions insulate application from specifics, eliminate

    redundant code, and handle common error conditions

    Underlying technology specifics still accessible (closures)

  • 8/8/2019 Spring Talk 111204

    4/57

    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

  • 8/8/2019 Spring Talk 111204

    5/57

    Spring Framework

  • 8/8/2019 Spring Talk 111204

    6/57

    Spring Application

  • 8/8/2019 Spring Talk 111204

    7/57

    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 locatesimplementation (pull)

    Martin Fowler calls Dependency Injection

  • 8/8/2019 Spring Talk 111204

    8/57

    Dependency Injection Variants Variations on dependency injection

    Interface based (Avalon)

    Constructor-based (PicoContainer, Spring) Setter-based (Spring)

    BeanFactory provides configuration framework to

    initialize and wire JavaBeans

    org.springframework.beans andorg.springframework.context

    Typically use the XmlBeanFactory, employing XML

    configuration files

  • 8/8/2019 Spring Talk 111204

    9/57

    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 toother beans

    Built-in support for defining Lists, Maps, Sets,and Properties collection types.

    Custom PropertyEditors may be defined toconvert string values to other, arbitrary types.

  • 8/8/2019 Spring Talk 111204

    10/57

    XmlBeanFactory Example Property and constructor based IoC

    1

    1

  • 8/8/2019 Spring Talk 111204

    11/57

    Bean Creation Direct instantiation

    BeanFactory instantiation Same syntax but class is subclass of BeanFactory

    getObject() called to obtain Bean

    Static Factory

    Instance Factory Method

  • 8/8/2019 Spring Talk 111204

    12/57

    Bean Creation Beans may be singletons or prototypes

    Attributesingleton=false causes instantiation

    with each getBean() lookup Singleton is default

    XmlBeanFactory pre-instantiates singletons

    May be overridden on per-instance basis by lazy-

    init=true

    Beans may also be marked abstract, allowingreuse of attribute values through inheritance

  • 8/8/2019 Spring Talk 111204

    13/57

    Autowiring Properties Beans may be auto-wired (rather than using )

    Per-bean attribute autowire

    Explicit settings override

    autowire=name

    Bean identifier matches property name

    autowire=type

    Type matches other defined bean

    autowire=constructor Match constructor argument types

    autowire=autodetect

    Attempt by constructor, otherwise type

  • 8/8/2019 Spring Talk 111204

    14/57

    Dependency Checking Ensures properties are defined

    Per-bean attribute dependency-check

    None required by default

    Verifies autowiring succeeded

    simple

    all but collaborators

    object collaborators only

    all

    Collaborators, primitive types, and collections

  • 8/8/2019 Spring Talk 111204

    15/57

    Lifecycle Customization Can define init method called after properties set

    init-method=

    Can define destroy method as shutdown hook

    destroy-method=

    May alternatively implement InitializingBean

    and/or DisposableBean At cost of Spring dependency

  • 8/8/2019 Spring Talk 111204

    16/57

    BeanFactory Miscellany BeanFactoryAware interface provides BeanFactory for

    bean

    setBeanFactory(BeanFactory)

    BeanNameAware interface provides bean name

    setBeanName(String)

    FactoryBean for beans which are themselves factories

    Object getObject()

    Boolean isSingleton()

    Class getObjectType()

  • 8/8/2019 Spring Talk 111204

    17/57

    BeanFactory Usage

    InputStream is = new FileInputStream("beans.xml");XmlBeanFactory factory = new XmlBeanFactory(is);MyBeanClass bean = (MyBeanClass)factory.getBean(myBean);

    ApplicationContext ctx = newClassPathXmlApplicationContext("beans.xml");MyBeanClass bean = (MyBeanClass)ctx.getBean(myBean);

    OR

  • 8/8/2019 Spring Talk 111204

    18/57

    ApplicationContext Extends functionality of BeanFactory

    Pre-instantiates singleton beans

    Detects and registers BeanPostProcessors andBeanFactoryPostProcessors

    Supports nesting of contexts

    ApplicationListenerand ApplicationEvents

    Initialized and closed predefined

    Custom may be created

    MessageSourceprovides i18n messaging

    Contains list of bundle base names

  • 8/8/2019 Spring Talk 111204

    19/57

    Web Initialization Web applications may use

    ContextLoaderListener to initialize Spring

    contextConfigLocation/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml

    org.springframework.web.context.ContextLoaderListener

    web.xml

    Automatically done by Spring DispatcherServlet

  • 8/8/2019 Spring Talk 111204

    20/57

    Specialized Beans MethodInvokingFactoryBean

    Invokes method on registered beans or any static

    methods

    Stores return value

    SingletonBeanFactoryLocator and

    ContextSingletonBeanFactoryLocator Useful for sharing BeanFactories

    Eliminate duplication of beans in multiple similar

    factories or contexts

  • 8/8/2019 Spring Talk 111204

    21/57

    ApplicationContext customization Defined beans inheriting from

    BeanFactoryPostProcessorare detected and invoked

    CustomEditorConfigurer

    Registers customPropertyEditors for converting

    configuration string values to specific types

    AutoProxyCreators

    Wrap beans in proxies based on various criteria (name,metadata, etc)

    PropertyResourceConfigurer Sets from property file and/or system properties

  • 8/8/2019 Spring Talk 111204

    22/57

    ApplicationContext Example

    database.properties

    ${database.connection.driver_class}

    ${database.connection.url}

  • 8/8/2019 Spring Talk 111204

    23/57

    Spring AOP

  • 8/8/2019 Spring Talk 111204

    24/57

    AOP Fundamentals Aspect-oriented programming (AOP) provides for

    simplified application of cross-cutting concerns

    Transaction management

    Security

    Logging

    Auditing

    Locking

    AOP sometimes (partially) achieved via Decorators or

    Proxies

    CORBA Portable Interceptors

    Servlet Filters

  • 8/8/2019 Spring Talk 111204

    25/57

    AOP Fundamentals Aspect - Implementation of a cross-cutting concern.

    Spring Advisors or Interceptors

    Joinpoint - Execution point to target Typically, methods

    Advice - Action taken at a particular joinpoint.

    Pointcut - A set of joinpoints specifying where advice

    should be applied (e.g. Regular expression) Introduction/Mixin - Adding methods or fields to an

    advised class.

    Weaving - Assembling aspects into advised objects.

  • 8/8/2019 Spring Talk 111204

    26/57

    Spring AOP Generally, applies aspects to beans using BeanFactory

    Uses Dynamic Proxies if interface available

    otherwise CGLIB

    CGLIB creates derived class which proxies requests

    Bean class may not be final

    Less capable than AspectJ

    does not have field interception only runtime weaving solution is available

    Closer integration with AspectJ anticipated

  • 8/8/2019 Spring Talk 111204

    27/57

    Spring Pointcuts Pointcut applicability to a class may be evaluated

    statically or dynamically

    Spring only creates proxies where necessary

    public interface Pointcut {ClassFilter getClassFilter();MethodMatcher getMethodMatcher();

    }public interface ClassFilter {

    boolean matches(Class clazz);}

  • 8/8/2019 Spring Talk 111204

    28/57

    Pointcuts (cont'd)

    public interface MethodMatcher {boolean matches(Method m, Class targetClass);

    boolean isRuntime();boolean matches(Method m, Class targetClass, Object[] args);

    }

    Pointcut may be statically or dynamically

    evaluated based on isRuntime()

    Abstract class StaticMethodMatcherPointcut

    requires override of 1st method only

    Only called if isRuntime() == true

  • 8/8/2019 Spring Talk 111204

    29/57

    Pointcuts (cont'd) Spring predefined pointcuts

    In org.springframework.aop.support package

    RegexpMethodPointcut Union of multiple regular expressions

    Uses Jakarta ORO package

    ControlFlowPointcut

    Similar to AspectJ cflow

    Applied if call stack includes specific class and, optionally,method

    UnionPointcut

    Merges pointcuts

  • 8/8/2019 Spring Talk 111204

    30/57

    Spring Advice Can have per-class or per-instance Advice

    Spring provides several Advice types

    Around Advice AOP Alliance compliant

    Must call invocation.proceed() to call target

    public class MyAdvice implements AroundAdvice {

    Object invoke(MethodInvocation invocation) {// change arguments, start transaction, lock, etc.invocation.proceed();// change return value, stop transaction, unlock,etc.

    }}

  • 8/8/2019 Spring Talk 111204

    31/57

    Spring Advice MethodBeforeAdvice

    void before(Method m, Object[] args, Object target)

    Cannot alter return type

    ThrowsAdvice

    Marker interface

    Implementors define methods of form:

    afterThrowing([Method], [args], [target], subclassOfThrowable)

    AfterReturningAdvice

    void afterReturning(Object returnValue, Method, m,

    Object[] args, Object target)

    Cannot modify return value

  • 8/8/2019 Spring Talk 111204

    32/57

    Spring Advice IntroductionInterceptor provides ability to define

    mixins

    public class RollbackAdvice extends DelegatingIntroductionInterceptorimplements RollbackSupport {

    Map map = new HashMap();

    void rollback(Date date) {// rollback to state at given time

    }

    public Object invoke(MethodInvocation invocation) {// record change and time of change

    }}

  • 8/8/2019 Spring Talk 111204

    33/57

    InjectingAdviceSpring

  • 8/8/2019 Spring Talk 111204

    34/57

    InjectingAdvice (cont'd)

    myAdvisordebugInterceptor

    Advisors applied in order

    All methods

    using CGLibif none defined

  • 8/8/2019 Spring Talk 111204

    35/57

    Autoproxying Autoproxy bean definitions automatically proxy

    selected beans.

    BeanNameAutoProxyCreator Adds listed advisors/interceptors to beans

    with names matching regular expression

    DefaultAdvisorAutoProxyCreator

    Generic autoproxy infrastructure support

    Applies all advisors defined in the context toall beans, proxying appropriately

  • 8/8/2019 Spring Talk 111204

    36/57

    Metadata support Spring supports obtaining meta data Object

    attributes at class, method, and field level

    Not yet argument level (as JSR-175) Currently supports Jakarta Commons Attributes

    Support for JSR-175 in work

    Metadata support provided viaA

    ttributesinterface

    Amenable to mocking unlike JDK reflection and

    Commons static methods

  • 8/8/2019 Spring Talk 111204

    37/57

    Metadata autoproxying Configuration of autoproxying based on metadata

    attributes simplifies configuration

    Define custom attribute class

    Define Advisor with pointcut based on custom attribute

    Add Advisor in ApplicationContext with autoproxy

    Examples

    Transaction Attributes

    Security Attributes

    Pooling

    Mapping of controllers to URLs

  • 8/8/2019 Spring Talk 111204

    38/57

    Transactions

  • 8/8/2019 Spring Talk 111204

    39/57

    AOP Transactions Spring provides AOP support for declarative

    transactions

    Delegates to a PlatformTransactionManager

    instance

    DataSourceTransactionManager

    HibernateTransactionManager JdoTransactionManager

    JtaTransactionManager

  • 8/8/2019 Spring Talk 111204

    40/57

    Transaction Configuration

    com/../model/*.hbm.xml

  • 8/8/2019 Spring Talk 111204

    41/57

    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

    Also allows definition of pre- and post-

    interceptors (e.g. for security)

  • 8/8/2019 Spring Talk 111204

    42/57

    Injecting Transaction Support

  • 8/8/2019 Spring Talk 111204

    43/57

    Transaction Autoproxy

    Caches metadatafrom classes

    Generic autoproxysupport

    Applies transactionusing transactionManager

    Invokes interceptorbased on attributes

  • 8/8/2019 Spring Talk 111204

    44/57

    Data Access

  • 8/8/2019 Spring Talk 111204

    45/57

    Data Access DAO support provides pluggable framework for

    persistence

    Currently supports JDBC, Hibernate, JDO, andiBatis

    Defines consistent exception hierarchy (based onRuntimeException)

    Provides abstract Support classes for eachtechnology

    Template methods define specific queries

  • 8/8/2019 Spring Talk 111204

    46/57

    Hibernate DAO Examplepublic class ReservationDaoImpl extends HibernateDaoSupport

    implements ReservationDao {public Reservation getReservation (Long orderId) {return (Reservation)getHibernateTemplate().load(Reservation .class,

    orderId);}

    public void saveReservation (Reservation r) {getHibernateTemplate().saveOrUpdate(r);

    }

    public void remove(Reservation Reservation) {getHibernateTemplate().delete(r);

    }

  • 8/8/2019 Spring Talk 111204

    47/57

    Hibernate DAO (contd)

    public Reservation[] findReservations(Room room) {

    List list = getHibernateTemplate().find(

    "from Reservation reservation +

    where reservation.resource =? +

    order by reservation.start",

    instrument);

    return (Reservation[]) list.toArray(new Reservation[list.size()]);

  • 8/8/2019 Spring Talk 111204

    48/57

    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 > :rangeStart and r.start < :rangeEnd );

    query.setDate("rangeStart", range.getStartDate()

    query.setDate("rangeEnd", range.getEndDate())

    return query.list();}

    });

    return (Reservation[]) list.toArray(new Reservation[list.size()]);

    }

    }

  • 8/8/2019 Spring Talk 111204

    49/57

    Hibernate Example

    com/jensenp/Reservation/Room.hbm.xml

    com/jensenp/Reservation/Reservation.hbm.xmlcom/jensenp/Reservation/Resource.hbm.xml

    ${hibernate.dialect}${hibernate.hbm2ddl.auto}${hibernate.show_sql}

  • 8/8/2019 Spring Talk 111204

    50/57

    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

  • 8/8/2019 Spring Talk 111204

    51/57

    Web Framework

  • 8/8/2019 Spring Talk 111204

    52/57

    DispatcherServlet The DispatcherServlet is the Spring Front

    Controller

    InitializesWebApplicationContext

    Uses /WEB-INF/[servlet-name]-servlet.xmlby

    default

    WebApplicationContext is bound intoServletContext

  • 8/8/2019 Spring Talk 111204

    53/57

    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

  • 8/8/2019 Spring Talk 111204

    54/57

    Dispatcher Servlet Configuration MultipartResolver

    Handling of file upload

    LocaleResolver

    Default uses HTTP accept header, cookie, or

    session

  • 8/8/2019 Spring Talk 111204

    55/57

    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

  • 8/8/2019 Spring Talk 111204

    56/57

    Controller Implementations CommandControllers bind parameters to data

    objects

    AbstractCommandController

    AbstractFormController

    SimpleFormController

    WizardFormController

  • 8/8/2019 Spring Talk 111204

    57/57

    References Springs homepage: http://www.springframework.org

    Introducing the Spring Framework by Rod Johnson:

    http://theserverside.com/news/thread.jsp?thread_id=21893

    Inversion of control containers and dependency injection by

    Martin Fowler:

    http://www.martinfowler.com/articles/injection.html

    AOP Alliance: http://aopalliance.sourceforge.net