Introduction to Spring Framework and Spring IoC

Embed Size (px)

Citation preview

Introduction to Spring IoC Container

By Sherif M. Ali

Agenda (Yes, I admit I have one!)

Dependencies Common Dependencies

Problems that dependencies create

Dependency Injection Inversion of Control

Advantages

Drawbacks

SpringLinkedIn Spring Usage

Seven Modules of Spring framework

Spring Core

Spring Context / Web Context

Integrating Spring with other web frameworks:Example I: Integrating with JSF

Unit TestingUnit Testing in Spring

Common Dependencies

Application Layers:

Presentation Layer

Business Layer

Data Access Layer

External Services:

Web Services

WCF (Windows Communication Foundation) Services

External Components:

Frameworks and Libraries

3rd Party Components

Application Layer Dependencies

Problems that dependencies create

Tight coupling of software components.

Software becomes hard to maintain.

Difficult to isolate when testing.

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 InstantiationSimplest, 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.

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.

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.

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.

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.

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+).

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

The seven modules of the Spring framework

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.

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.

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.

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.

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.

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.

In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes.

In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging.

Object Oriented Programming (OOP)

Aspect Oriented Programming (AOP)

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.

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.

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.

BeanFactory (Cont.)

Spring provides several out-of-the-box implementations of the bean factory using:

XMLXmlBeanFactory class allows you to configure the various application classes and their dependencies in XML files.

AnnotationsSpring annotation support.

JavaConfigConfiguration done using Java. Uses annotations and replaces the XML config with Java code.

....

It is possible to mix and match definition styles

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.

XmlFactoryBean

A Spring configuration file is created with the bean definitions:

Example: spring-config.xml

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.

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 containingconfiguration for different areas:

applicationContext.xml

dao.xml

...

XmlFactoryBean (Cont.)

Creating a Spring IoC container using XmlBeanFactory:

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

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

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

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

Construction Injection

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

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; }}

Spring Context/Web Context

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

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");

Spring Context (Cont.)

A Servlet listener can be registered to initialize application context in a web applicationcommonly 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.

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.

Declare a ContextLoaderListener in a standard J2EE servlet web.xml

org.springframework.web.context.ContextLoaderListener

Integrating Spring with other web frameworks (Cont.)

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

contextConfigLocation /WEB-INF/applicationContext*.xml

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);

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.

Edit faces-context.xml. In element add an element and a element referencing Spring's DelegatingVariableResolve

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

org.springframework.web.jsf.DelegatingVariableResolver

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.

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.

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

Example: Unit Testing in Spring

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfigurationpublic 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); }}

Example: Unit Testing in Spring (Cont.)

SetterMessageTest-Context.xml

Agenda

Dependencies Common Dependencies

Problems that dependencies create

Dependency Injection Inversion of Control

Advantages

Drawbacks

SpringLinkedIn Spring Usage

Seven Modules of Spring framework

Spring Core

Spring Context / Web Context

Integrating Spring with other web frameworks:Example I: Integrating with JSF

Unit TestingUnit Testing in Spring

Thank you

Q&A

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 \lib\jakarta-commons) and log4j*.jar (from \lib\log4j).

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