KEMBAR78
Introduction to Spring Framework and Spring IoC | ODP
Introduction to Spring IoC Container
By Sherif M. Ali
Agenda (Yes, I admit I have one!)



 Dependencies                             Spring Core
  – Common Dependencies                       –
    – Problems that dependencies create    Spring Context / Web Context
    –                                         –
 Dependency Injection                     Integrating Spring with other
    – Inversion of Control
    – Advantages                           web frameworks:
                                              –Example I: Integrating with JSF
    – Drawbacks
                                              –
    –
 Spring                                   Unit Testing
                                              –Unit Testing in Spring
    –LinkedIn Spring Usage
                                              –
    –Seven Modules of Spring framework
                                          
                                             –

    August 21, 2012
                                          
Common Dependencies

 Application Layers:              Application Layer Dependencies



     –Presentation Layer
     –Business Layer
     –Data Access Layer
     –
      –
●   External Components:
●

●
      –
    ● Frameworks and Libraries
      –
    ●
      –3rd Party Components
     –
     –


 External Services:



     –Web Services
     –WCF (Windows Communication
     Foundation) Services
     –

     August 21, 2012
Problems that dependencies create



 Tight coupling of software components.

 Software becomes hard to maintain.

 Difficult to isolate when testing.




    August 21, 2012
Dependency Injection



 DI describes how one object resolves or finds other objects on which it needs to
  invoke some methods.

 There are several ways to achieve DI:

    –Direct Instantiation
      •Simplest, dependent object is directly instantiated using the new operator.
      •
    –FactoryHelper (Factory Pattern)
      •The factory method consolidates the use of the new operator and supplies
      appropriate object instances based on some input.
    –
    –Locate in Registry Service (Service Locator Pattern)
      •Example, look-up of EJB object references on the JNDI registry service.
      •
    –
    August 21, 2012
Dependency Injection (Cont.)



 All these previous strategies are commonly called pull dependency injection.

 The dependent Object is pulled in by the object that ultimately uses it.

 Pull method can be thought of as dependency resolution rather than true
  dependency injection.

 True Dependency Injection is achieved by push dependency injection.

 Inverse Of Control (IOC) is a push dependency injection.

EJB containers also provide push dependency injection.
         •
    August 21, 2012
    –
Inversion Of Control - "Don't call us; we'll call you."



“A software design pattern and set of associated programming techniques in which
the flow of control of a system is inverted in comparison to the traditional interaction
mode.”

 In this approach, an external container of application framework creates and
  passes(Injects) the dependent object to the object that requires it.

 Components are no longer in charge of managing their dependencies, rather it's
  dependencies will be injected at run time.





    August 21, 2012
Dependency Injection Pattern



Advantages:


 Dependency injection promotes loose coupling by adding the ability to specify
  component dependencies at run time.

 Promotes good object-oriented design and reuse – object composition rather than
  reuse by inheritance.

 Increases testability of individual components and facilitates test-driven
  development (TDD).
         •Objects can be easily tested because they do not require any particular container to
         run. They can be tested as long as the dependencies are injected by some
         mechanism.
 Addresses the need for plug-able architecture.
    August 21, 2012
Dependency Injection Pattern



Drawbacks of Dependency Injection:


 The dependencies are generally hard-coded in XML configuration files that are
  proprietary and nonstandard.

 Wiring instances together can become a hazard if there are too many instances
  and many dependencies that need to be addressed.

 Dependency on XML-based metadata and excessive use of reflection and
  bytecode manipulation may impact application performance.




    August 21, 2012
Spring Framework



 The Spring Framework is an open source application framework for the Java
  platform.

 The first version was written by Rod Johnson, who released the framework with
  the publication of his book Expert One-on-One J2EE Design and Development in
  October 2002.

 The framework was first released under the Apache 2.0 license in June 2003.

 The current version is 3.0.6 (Requires Java 1.5+).




    August 21, 2012
LinkedIn Spring Usage



LinkedIn Stack: 99% Pure Java

                                The numbers:

                                ●22 million members
                                ●40 million page views/day

                                ●

                                    Engineering Process:

                                ●Release often (2-4 week
                                development cycles).
                                ●Strong focus on testing:
                                ●




                                  ● 6500+ unit and integration tests

                                     ●

                                Service Oriented Architecture




    August 21, 2012
The seven modules of the Spring framework









    August 21, 2012
The seven modules of the Spring framework (Cont.)




 Spring Core

    –The most fundamental part of the framework and provides the IoC and
    Dependency Injection features.
    –
    –The basic concept here is the BeanFactory, which provides a sophisticated
    implementation of the factory pattern which removes the need for programmatic
    singletons.
    –
           BeanFactory Creates, caches, wires together, and manages application objects.
    –
    –Allows you to decouple the configuration and specification of dependencies
    from your actual program logic.


    August 21, 2012
The seven modules of the Spring framework (Cont.)




 Spring Context

    –Build on Spring Core.
    –
    –It provides context information to the Spring framework.
    –
    –The Spring context includes enterprise services such as JNDI, EJB, e-mail,
    internalization, validation, and scheduling functionality.
    –
    –




    August 21, 2012
The seven modules of the Spring framework (Cont.)




 Spring Web Context

    –Provides basic web-oriented integration features, such as multipart file-upload
    functionality, the initialization of the IoC container using servlet listeners and a
    web-oriented application context.
    –
    –When using Spring together with WebWork or Struts, this is the package to
    integrate with.




    August 21, 2012
The seven modules of the Spring framework (Cont.)



 Spring DAO

    –Provides a JDBC-abstraction layer that removes the need to do tedious JDBC
    coding and parsing of database-vendor specific error codes.
    –
    –The JDBC package provides a way to do programmatic as well as declarative
    transaction management, not only for classes implementing special interfaces,
    but for all your POJOs (plain old Java objects).
    –
    –Spring JDBC/DAO makes life very easy by removing the common code in
    templates (Template Pattern). The templates provide suitable extension points
    to plug-in custom code.
    –
    –This makes the data access code very clean and prevents problems such as
    connection leaks, because the Spring Framework ensures that all data-base
    resources are released properly.
    August 21, 2012
The seven modules of the Spring framework (Cont.)



 Spring ORM

    –Build on Spring DAO.
    –
    –Provides integration layers ,using ORM templates, for popular object-relational
    mapping APIs, including JPA, JDO and Hibernate.
    –
    –
    –
    –




    August 21, 2012
Aspect-oriented programming (AOP)



 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.

 The core construct of AOP is the aspect, which encapsulates behaviors affecting
  multiple classes into reusable modules.


    Object Oriented Programming (OOP)            Aspect Oriented Programming (AOP)

    In a typical object-oriented development     In an AOP approach you would instead
    approach you might implement logging         modularize the logging services and apply
    functionality by putting logger statements   them declaratively to the components that
    in all your methods and Java classes.        required logging.



     August 21, 2012
The seven modules of the Spring framework (Cont.)




 Spring AOP

    –Provides an AOP Alliance-compliant aspect-oriented programming
    implementation allowing you to define, for example, method-interceptors and
    pointcuts to cleanly decouple code implementing functionality that should
    logically speaking be separated.
    –
    –Using source-level metadata functionality you can also incorporate all kinds of
    behavioral information into the code.




    August 21, 2012
The seven modules of the Spring framework (Cont.)




 Spring MVC

    –Provides a Model-View-Controller (MVC) implementation for web-applications.
    –
    –Spring's MVC framework provides a clean separation between domain model
    code and web forms, and allows you to use all the other features of the Spring
    Framework.




    August 21, 2012
Spring Core
BeanFactory



 The org.springframework.beans.factory.BeanFactory interface provides the basis
  for Spring's IOC container.

 An implementation of the Factory design pattern enables objects to be created
  and retrieved by name. BeanFactory can also manage relationships between
  objects.

 In short, a bean factory, like JNDI, is a registry of application objects.


    –
    –
    –

    August 21, 2012
BeanFactory (Cont.)



 Spring provides several out-of-the-box implementations of the bean factory using:

    –XML
        •XmlBeanFactory class allows you to configure the various application
        classes and their dependencies in XML files.
        •
    –Annotations
        •Spring annotation support.
    –
    –JavaConfig
        •Configuration done using Java. Uses annotations and replaces the XML
        config with Java code.
    –....

 It is possible to mix and match definition styles
   August 21, 2012
Bean Factory (Cont.)



 BeanFactory supports two object modes:

    –Singleton mode provides a shared instance of the object with a particular
    name, which will be retrieved on lookup. Singleton is the default and most often
    used object mode. It is ideal for stateless service objects.
    –
    –
    –Prototype mode ensures that each retrieval will result in the creation of an
    independent object. Prototype mode would be best used in a case where each
    user needed to have his or her own object.
    –




    August 21, 2012
XmlFactoryBean



A Spring configuration file is created with the bean definitions:
Example: spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >

     <bean name="mybean" class="com.ibm.MySampleBean" />
</beans>


●
     Each bean definition can be a POJO (defined by class name and JavaBean
    initialization properties) or a FactoryBean.

●    The FactoryBean interface adds a level of indirection to the applications built using
    the Spring framework.
●




      August 21, 2012
XmlFactoryBean (Cont.)



●
    Beans defined in XML files are lazily loaded,which means that the beans themselves
    will not be instantiated until they are needed.

●    The XML configuration can be split amoung multiple files. With each file containing
    configuration for different areas:

       ●   applicationContext.xml
       ●   dao.xml
       ●   ...




      August 21, 2012
XmlFactoryBean (Cont.)



●   Creating a Spring IoC container using XmlBeanFactory:

    Resource res = new FileSystemResource("spring-config.xml");
    BeanFactory factory = new XmlBeanFactory(res);


●   To retrieve a bean from BeanFactory we can simply call the getBean() method
    passing in the name of the bean we want to retrieve:

    MyBean mybean = (MyBean) factory.getBean("mybean");




      August 21, 2012
Types of Dependency Injection


 Construction Injection

    –The dependent object is passed as part of the constructor call.

 Property/Setter/Mutator Injection

    –The dependent object is passed as a parameter to the setter method.

 Interface Injection

    –Services need to implement a dedicated interface through which they are
    provided with an object from which they can look up dependencies (for example,
    additional needed services).
    –
     N.B: Spring doesn't use this type of injection
          •
    August 21, 2012
Construction Injection

public class CarServiceImpl implements CarService{
    private CarDao carDao;
    public void CarServiceImpl (CarDao carDao, String carName){
          this.carDao = carDao;
    }
}


<bean name="carDao" class="com.apress.simpleapp.dao.CatDaoImpl" />

<bean name="carService" class="com.apress.simpleapp.service.CarServiceImpl">
    <constructor-arg>
        <ref bean="carDao"/>
    </constructor-arg>
    <constructor-arg value=”Fiat”/>
</beans>



        August 21, 2012
Setter Injection

The CarService object needs data access objects (DAO) to execute data-base
operations. The data access objects are injected via setter methods


    public class CarServiceImpl implements CarService{
      private CarDao carDao;

         public void setCarDao(CarDao carDao){
           this.carDao = carDao;
         }
    }



  <bean name="carDao" class="com.apress.simpleapp.dao.CatDaoImpl" />

  <bean name="carService" class="com.apress.simpleapp.service.CatServiceImpl">
       <property name="carDao" ref="carDao" />
  </bean>



   August 21, 2012
Spring Context/Web
                        Context



August 21, 2012
Spring Context



 The org.springframework.context.ApplicationContext interface provides the basis
  for Spring's context package.

 ApplicationContext builds on top of the BeanFactory (it's a subclass) and adds
  other functionality such as:

    – Easier integration with Springs AOP features.
    –
    – MessageSource, providing access to messages in i18n (internationalization)
    style.
    –
    –Access to resources, such as URLs and files
    –
    –
    –
    –
    August 21, 2012
Spring Context (Cont.)



    –Event propagation to beans implementing the ApplicationListener interface.
    –
    –Loading of multiple (hierarchical) contexts, allowing each to be focused on one
    particular layer, for example the web layer of an application.
    –
    –
 Creating an ApplicationContext is similar to creating a bean factory and doesn't
  require any alterations in the configuration file.

          ApplicationContext context = new ClassPathXmlApplicationContext("spring-
          config.xml");




    August 21, 2012
Spring Context (Cont.)



 A Servlet listener can be registered to initialize application context in a web
  application—commonly called web application context.

    –The listener looks for the configuration file at a specific location within the web
    application archive to start the web application context.






    August 21, 2012
Integrating Spring with other web frameworks



 Spring provides its own web framework (SpringMVC), while at the same time
  providing integration with a number of popular third party web frameworks.

 Web layers serve as one of the entry points into a server side application, and it
  delegates to service objects (facades) defined in a service layer to satisfy
  business specific use cases.

1) Declare a ContextLoaderListener in a standard J2EE servlet web.xml
   –
       <listener>
          <listener
      -class>org.springframework.web.context.ContextLoaderListener</listener-
      class>
       </listener>
   –
   1)
    August 21, 2012
Integrating Spring with other web frameworks (Cont.)



2) Add the configuration(s) location in the context-param
3)




<context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
If the contextConfigLocation context parameter is not specified, the ContextLoaderListener
will look for a file called /WEB-INF/applicationContext.xml to load.


●
     All Java web frameworks are built on top of the Servlet API, and so one can use
     the following code snippet to get access to the ApplicationContext created by the
     ContextLoaderListener
                         WebApplicationContext ctx =
                            WebApplicationContextUtils.getWebApplicationContext(servletContext);
       August 21, 2012
Example I: Integrating with JSF



 JavaServer Faces (JSF) is an increasingly popular component-based, event-
  driven web framework.
 The key class in Spring's JSF integration is the DelegatingVariableResolver class.

1) Edit faces-context.xml. In <faces-config/> element add an <application/>
 element and a <variable-resolver/> element referencing Spring's
 DelegatingVariableResolve
2)         <variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver
3)         </variable-resolver>

The DelegatingVariableResolver will first delegate value lookups to the default
resolver of the underlying JSF implementation, and then to Spring's 'business
context' WebApplicationContext.


    August 21, 2012
Unit Testing



●
    There are two types of testing that developers typically perform before they release
    code into production:
●

     ●
         Functional testing: is the testing done when your application is mostly built and
         we want to make sure that everything works according to the functional
         requirements.
     ●

     ●
         Unit testing: is the process by which we test each component of your application
         in isolation.
     ●

           ●
               Unit testing can be done far in advance of functional testing and code release.
           ●

           ●
               Spring makes unit testing easy because each component is intended to be an
               entity unto itself – callable from anywhere.

      August 21, 2012
Unit Testing (Cont.)



●
    Unit testing is an important part of the development process.
●


●
    Some methodologies, including Agile, require that the unit test be written before the
    class that it will be testing. Writing Unit test first gives a clear idea of the use case for
    the class files.
●


●
    There are several third party and open source products that can help set up and
    conduct unit tests such as JUnit.
●


●
    Unit tests can be run manually or from a build framework such as Maven.




      August 21, 2012
Unit Testing in Spring



●
    Spring has unit test support.
●


●
    Unit tests are annotated with @RunWith(SpringJunit4ClassRunner.class) and
    @ContextConfiguration.
●


●
    @contextConfiguration default to loading an XML configuration file from the
    package and name of the test plus '-context.xml'.
●

     ●
         Example: for com.ibm.test.IntensiveCodeTest the default XML file is
         com/ibm/test/IntensiveCodeTest-context.xml




      August 21, 2012
Example: Unit Testing in Spring

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SetterMessageTest {
    final Logger logger = LoggerFactory.getLogger(SetterMessageTest.class);
    @Autowired
    private SetterMessage message = null;


    /** Tests message. */
    @Test
    public void testMessage() {
        assertNotNull("Constructor message instance is null.", message);
        String msg = message.getMessage();
        assertNotNull("Message is null.", msg);
        String expectedMessage = "Spring is fun.";
        assertEquals("Message should be '" + expectedMessage + "'.", expectedMessage, msg);
        logger.info("message='{}'", msg);
    }
        August 21, 2012
}
Example: Unit Testing in Spring (Cont.)


SetterMessageTest-Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd">


  <bean id="message"
       class="org.springbyexample.di.xml.SetterMessage">
     <property name="message" value="Spring is fun." />
  </bean>


</beans>




    August 21, 2012
Agenda



 Dependencies                             Spring Core
  – Common Dependencies                       –
    – Problems that dependencies create    Spring Context / Web Context
    –                                         –
 Dependency Injection                     Integrating Spring with other
    – Inversion of Control
    – Advantages                           web frameworks:
                                              –Example I: Integrating with JSF
    – Drawbacks
                                              –
    –
 Spring                                   Unit Testing
                                              –Unit Testing in Spring
    –LinkedIn Spring Usage
                                              –
    –Seven Modules of Spring framework
                                          
                                             –

    August 21, 2012
                                          
Thank you
                    Q&A




August 21, 2012
Apendix I : Spring Installation



 Download Spring from http://www.springframework.org/download
 Select the -with-dependencies.zip to get also all required plugins. At the time of writing latest version is
  3.0.6
 The folder dist contain the Spring container "spring.jar".
 The folder lib contains additional require libraries.
 A minimal Spring application requires the spring.jar, commons-logging.jar (from libjakarta-commons)
  and log4j*.jar (from liblog4j).





    August 21, 2012
References



 Pro Java EE Spring Patterns by Dhrubojy Kayal
 The Spring series, Part 1 by Naveen Balani (
  http://www.ibm.com/developerworks/web/library/wa-spring1/)
 SpringSource.org
 LinkedIn – A professional Network built with Java Technologies and Agile Practices (
  http://www.slideshare.net/linkedin/linkedins-communication-architecture)
 Spring by Example (http://www.springbyexample.org)





    August 21, 2012

Introduction to Spring Framework and Spring IoC

  • 1.
    Introduction to SpringIoC Container By Sherif M. Ali
  • 2.
    Agenda (Yes, Iadmit I have one!)  Dependencies  Spring Core – Common Dependencies – – Problems that dependencies create  Spring Context / Web Context – –  Dependency Injection  Integrating Spring with other – Inversion of Control – Advantages web frameworks: –Example I: Integrating with JSF – Drawbacks – –  Spring  Unit Testing –Unit Testing in Spring –LinkedIn Spring Usage – –Seven Modules of Spring framework   – August 21, 2012 
  • 3.
    Common Dependencies  ApplicationLayers: Application Layer Dependencies  –Presentation Layer –Business Layer –Data Access Layer – – ● External Components: ● ● – ● Frameworks and Libraries – ● –3rd Party Components – –  External Services:  –Web Services –WCF (Windows Communication Foundation) Services –  August 21, 2012
  • 4.
    Problems that dependenciescreate  Tight coupling of software components.   Software becomes hard to maintain.   Difficult to isolate when testing. August 21, 2012
  • 5.
    Dependency Injection  DIdescribes how one object resolves or finds other objects on which it needs to invoke some methods.   There are several ways to achieve DI:  –Direct Instantiation •Simplest, dependent object is directly instantiated using the new operator. • –FactoryHelper (Factory Pattern) •The factory method consolidates the use of the new operator and supplies appropriate object instances based on some input. – –Locate in Registry Service (Service Locator Pattern) •Example, look-up of EJB object references on the JNDI registry service. • – August 21, 2012
  • 6.
    Dependency Injection (Cont.) All these previous strategies are commonly called pull dependency injection.   The dependent Object is pulled in by the object that ultimately uses it.   Pull method can be thought of as dependency resolution rather than true dependency injection.   True Dependency Injection is achieved by push dependency injection.   Inverse Of Control (IOC) is a push dependency injection.  EJB containers also provide push dependency injection. • August 21, 2012 –
  • 7.
    Inversion Of Control- "Don't call us; we'll call you." “A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode.”   In this approach, an external container of application framework creates and passes(Injects) the dependent object to the object that requires it.   Components are no longer in charge of managing their dependencies, rather it's dependencies will be injected at run time.   August 21, 2012
  • 8.
    Dependency Injection Pattern Advantages: Dependency injection promotes loose coupling by adding the ability to specify component dependencies at run time.   Promotes good object-oriented design and reuse – object composition rather than reuse by inheritance.   Increases testability of individual components and facilitates test-driven development (TDD). •Objects can be easily tested because they do not require any particular container to run. They can be tested as long as the dependencies are injected by some mechanism.  Addresses the need for plug-able architecture. August 21, 2012
  • 9.
    Dependency Injection Pattern Drawbacksof Dependency Injection:  The dependencies are generally hard-coded in XML configuration files that are proprietary and nonstandard.   Wiring instances together can become a hazard if there are too many instances and many dependencies that need to be addressed.   Dependency on XML-based metadata and excessive use of reflection and bytecode manipulation may impact application performance. August 21, 2012
  • 10.
    Spring Framework  TheSpring Framework is an open source application framework for the Java platform.   The first version was written by Rod Johnson, who released the framework with the publication of his book Expert One-on-One J2EE Design and Development in October 2002.   The framework was first released under the Apache 2.0 license in June 2003.   The current version is 3.0.6 (Requires Java 1.5+). August 21, 2012
  • 11.
    LinkedIn Spring Usage LinkedInStack: 99% Pure Java The numbers:  ●22 million members ●40 million page views/day ● Engineering Process: ●Release often (2-4 week development cycles). ●Strong focus on testing: ● ● 6500+ unit and integration tests ● Service Oriented Architecture August 21, 2012
  • 12.
    The seven modulesof the Spring framework   August 21, 2012
  • 13.
    The seven modulesof the Spring framework (Cont.)  Spring Core  –The most fundamental part of the framework and provides the IoC and Dependency Injection features. – –The basic concept here is the BeanFactory, which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons. – BeanFactory Creates, caches, wires together, and manages application objects. – –Allows you to decouple the configuration and specification of dependencies from your actual program logic. August 21, 2012
  • 14.
    The seven modulesof the Spring framework (Cont.)  Spring Context  –Build on Spring Core. – –It provides context information to the Spring framework. – –The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. – – August 21, 2012
  • 15.
    The seven modulesof the Spring framework (Cont.)  Spring Web Context  –Provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context. – –When using Spring together with WebWork or Struts, this is the package to integrate with. August 21, 2012
  • 16.
    The seven modulesof the Spring framework (Cont.)  Spring DAO  –Provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. – –The JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects). – –Spring JDBC/DAO makes life very easy by removing the common code in templates (Template Pattern). The templates provide suitable extension points to plug-in custom code. – –This makes the data access code very clean and prevents problems such as connection leaks, because the Spring Framework ensures that all data-base resources are released properly. August 21, 2012
  • 17.
    The seven modulesof the Spring framework (Cont.)  Spring ORM  –Build on Spring DAO. – –Provides integration layers ,using ORM templates, for popular object-relational mapping APIs, including JPA, JDO and Hibernate. – – – – August 21, 2012
  • 18.
    Aspect-oriented programming (AOP) 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.   The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. Object Oriented Programming (OOP) Aspect Oriented Programming (AOP) In a typical object-oriented development In an AOP approach you would instead approach you might implement logging modularize the logging services and apply functionality by putting logger statements them declaratively to the components that in all your methods and Java classes. required logging. August 21, 2012
  • 19.
    The seven modulesof the Spring framework (Cont.)  Spring AOP  –Provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. – –Using source-level metadata functionality you can also incorporate all kinds of behavioral information into the code. August 21, 2012
  • 20.
    The seven modulesof the Spring framework (Cont.)  Spring MVC  –Provides a Model-View-Controller (MVC) implementation for web-applications. – –Spring's MVC framework provides a clean separation between domain model code and web forms, and allows you to use all the other features of the Spring Framework. August 21, 2012
  • 21.
  • 22.
    BeanFactory  The org.springframework.beans.factory.BeanFactoryinterface provides the basis for Spring's IOC container.   An implementation of the Factory design pattern enables objects to be created and retrieved by name. BeanFactory can also manage relationships between objects.   In short, a bean factory, like JNDI, is a registry of application objects.   – – – August 21, 2012
  • 23.
    BeanFactory (Cont.)  Springprovides several out-of-the-box implementations of the bean factory using:  –XML •XmlBeanFactory class allows you to configure the various application classes and their dependencies in XML files. • –Annotations •Spring annotation support. – –JavaConfig •Configuration done using Java. Uses annotations and replaces the XML config with Java code. –....   It is possible to mix and match definition styles  August 21, 2012
  • 24.
    Bean Factory (Cont.) BeanFactory supports two object modes:  –Singleton mode provides a shared instance of the object with a particular name, which will be retrieved on lookup. Singleton is the default and most often used object mode. It is ideal for stateless service objects. – – –Prototype mode ensures that each retrieval will result in the creation of an independent object. Prototype mode would be best used in a case where each user needed to have his or her own object. – August 21, 2012
  • 25.
    XmlFactoryBean A Spring configurationfile is created with the bean definitions: Example: spring-config.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" > <bean name="mybean" class="com.ibm.MySampleBean" /> </beans> ● Each bean definition can be a POJO (defined by class name and JavaBean initialization properties) or a FactoryBean. ● The FactoryBean interface adds a level of indirection to the applications built using the Spring framework. ● August 21, 2012
  • 26.
    XmlFactoryBean (Cont.) ● Beans defined in XML files are lazily loaded,which means that the beans themselves will not be instantiated until they are needed. ● The XML configuration can be split amoung multiple files. With each file containing configuration for different areas: ● applicationContext.xml ● dao.xml ● ... August 21, 2012
  • 27.
    XmlFactoryBean (Cont.) ● Creating a Spring IoC container using XmlBeanFactory: Resource res = new FileSystemResource("spring-config.xml"); BeanFactory factory = new XmlBeanFactory(res); ● To retrieve a bean from BeanFactory we can simply call the getBean() method passing in the name of the bean we want to retrieve: MyBean mybean = (MyBean) factory.getBean("mybean"); August 21, 2012
  • 28.
    Types of DependencyInjection  Construction Injection –The dependent object is passed as part of the constructor call.   Property/Setter/Mutator Injection  –The dependent object is passed as a parameter to the setter method.   Interface Injection  –Services need to implement a dedicated interface through which they are provided with an object from which they can look up dependencies (for example, additional needed services). – N.B: Spring doesn't use this type of injection • August 21, 2012
  • 29.
    Construction Injection public classCarServiceImpl implements CarService{ private CarDao carDao; public void CarServiceImpl (CarDao carDao, String carName){ this.carDao = carDao; } } <bean name="carDao" class="com.apress.simpleapp.dao.CatDaoImpl" /> <bean name="carService" class="com.apress.simpleapp.service.CarServiceImpl"> <constructor-arg> <ref bean="carDao"/> </constructor-arg> <constructor-arg value=”Fiat”/> </beans> August 21, 2012
  • 30.
    Setter Injection The CarServiceobject needs data access objects (DAO) to execute data-base operations. The data access objects are injected via setter methods public class CarServiceImpl implements CarService{ private CarDao carDao; public void setCarDao(CarDao carDao){ this.carDao = carDao; } } <bean name="carDao" class="com.apress.simpleapp.dao.CatDaoImpl" /> <bean name="carService" class="com.apress.simpleapp.service.CatServiceImpl"> <property name="carDao" ref="carDao" /> </bean> August 21, 2012
  • 31.
    Spring Context/Web Context August 21, 2012
  • 32.
    Spring Context  Theorg.springframework.context.ApplicationContext interface provides the basis for Spring's context package.   ApplicationContext builds on top of the BeanFactory (it's a subclass) and adds other functionality such as:  – Easier integration with Springs AOP features. – – MessageSource, providing access to messages in i18n (internationalization) style. – –Access to resources, such as URLs and files – – – – August 21, 2012
  • 33.
    Spring Context (Cont.) –Event propagation to beans implementing the ApplicationListener interface. – –Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application. – –  Creating an ApplicationContext is similar to creating a bean factory and doesn't require any alterations in the configuration file.  ApplicationContext context = new ClassPathXmlApplicationContext("spring- config.xml");  August 21, 2012
  • 34.
    Spring Context (Cont.) A Servlet listener can be registered to initialize application context in a web application—commonly called web application context.  –The listener looks for the configuration file at a specific location within the web application archive to start the web application context.   August 21, 2012
  • 35.
    Integrating Spring withother web frameworks  Spring provides its own web framework (SpringMVC), while at the same time providing integration with a number of popular third party web frameworks.   Web layers serve as one of the entry points into a server side application, and it delegates to service objects (facades) defined in a service layer to satisfy business specific use cases.  1) Declare a ContextLoaderListener in a standard J2EE servlet web.xml – <listener> <listener -class>org.springframework.web.context.ContextLoaderListener</listener- class> </listener> – 1) August 21, 2012
  • 36.
    Integrating Spring withother web frameworks (Cont.) 2) Add the configuration(s) location in the context-param 3) <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param> If the contextConfigLocation context parameter is not specified, the ContextLoaderListener will look for a file called /WEB-INF/applicationContext.xml to load. ● All Java web frameworks are built on top of the Servlet API, and so one can use the following code snippet to get access to the ApplicationContext created by the ContextLoaderListener WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); August 21, 2012
  • 37.
    Example I: Integratingwith JSF  JavaServer Faces (JSF) is an increasingly popular component-based, event- driven web framework.  The key class in Spring's JSF integration is the DelegatingVariableResolver class.  1) Edit faces-context.xml. In <faces-config/> element add an <application/> element and a <variable-resolver/> element referencing Spring's DelegatingVariableResolve 2) <variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver 3) </variable-resolver> The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext.  August 21, 2012
  • 38.
    Unit Testing ● There are two types of testing that developers typically perform before they release code into production: ● ● Functional testing: is the testing done when your application is mostly built and we want to make sure that everything works according to the functional requirements. ● ● Unit testing: is the process by which we test each component of your application in isolation. ● ● Unit testing can be done far in advance of functional testing and code release. ● ● Spring makes unit testing easy because each component is intended to be an entity unto itself – callable from anywhere.  August 21, 2012
  • 39.
    Unit Testing (Cont.) ● Unit testing is an important part of the development process. ● ● Some methodologies, including Agile, require that the unit test be written before the class that it will be testing. Writing Unit test first gives a clear idea of the use case for the class files. ● ● There are several third party and open source products that can help set up and conduct unit tests such as JUnit. ● ● Unit tests can be run manually or from a build framework such as Maven. August 21, 2012
  • 40.
    Unit Testing inSpring ● Spring has unit test support. ● ● Unit tests are annotated with @RunWith(SpringJunit4ClassRunner.class) and @ContextConfiguration. ● ● @contextConfiguration default to loading an XML configuration file from the package and name of the test plus '-context.xml'. ● ● Example: for com.ibm.test.IntensiveCodeTest the default XML file is com/ibm/test/IntensiveCodeTest-context.xml August 21, 2012
  • 41.
    Example: Unit Testingin Spring @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class SetterMessageTest { final Logger logger = LoggerFactory.getLogger(SetterMessageTest.class); @Autowired private SetterMessage message = null; /** Tests message. */ @Test public void testMessage() { assertNotNull("Constructor message instance is null.", message); String msg = message.getMessage(); assertNotNull("Message is null.", msg); String expectedMessage = "Spring is fun."; assertEquals("Message should be '" + expectedMessage + "'.", expectedMessage, msg); logger.info("message='{}'", msg); } August 21, 2012 }
  • 42.
    Example: Unit Testingin Spring (Cont.) SetterMessageTest-Context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="message" class="org.springbyexample.di.xml.SetterMessage"> <property name="message" value="Spring is fun." /> </bean> </beans> August 21, 2012
  • 43.
    Agenda  Dependencies  Spring Core – Common Dependencies – – Problems that dependencies create  Spring Context / Web Context – –  Dependency Injection  Integrating Spring with other – Inversion of Control – Advantages web frameworks: –Example I: Integrating with JSF – Drawbacks – –  Spring  Unit Testing –Unit Testing in Spring –LinkedIn Spring Usage – –Seven Modules of Spring framework   – August 21, 2012 
  • 44.
    Thank you Q&A August 21, 2012
  • 45.
    Apendix I :Spring Installation  Download Spring from http://www.springframework.org/download  Select the -with-dependencies.zip to get also all required plugins. At the time of writing latest version is 3.0.6  The folder dist contain the Spring container "spring.jar".  The folder lib contains additional require libraries.  A minimal Spring application requires the spring.jar, commons-logging.jar (from libjakarta-commons) and log4j*.jar (from liblog4j).  August 21, 2012
  • 46.
    References  Pro JavaEE Spring Patterns by Dhrubojy Kayal  The Spring series, Part 1 by Naveen Balani ( http://www.ibm.com/developerworks/web/library/wa-spring1/)  SpringSource.org  LinkedIn – A professional Network built with Java Technologies and Agile Practices ( http://www.slideshare.net/linkedin/linkedins-communication-architecture)  Spring by Example (http://www.springbyexample.org)  August 21, 2012