close

Spring is an open source framework created to simplify the complexity of enterprise application development. Spring framework addresses all tier of application development in a consistent manner. Spring framework provides a layered architecture comprising of well defined modules, where each modules can be used independently to simplify some area of enterprise development.

In this first article of the Spring Series , I introduce you to the Spring framework. I start by describing the functionality of the framework in terms of its underlying modules and then discuss two of the most interesting modules, Spring aspect-oriented programming (AOP), and the Inversion of Control (IOC) container. I then use several examples to demonstrate the workings of the IOC container in a typical application use case scenario. The examples will also lay the foundation for an expanded discussion, later in this series, of the how the Spring framework implements AOP constructs through Spring AOP.

Spring framework is a lightweight open source layered application framework created to simplify the complexity of enterprise application development. Spring has become the de facto framework for creating Java based enterprise applications.The Spring framework provides the following functionality:

  • Lightweight IoC container for lifecycle and dependency management of objects.
  • AOP functionality for modularizing cross-cutting concerns and providing services to Plain Old Java Object(POJOs) in a declarative fashion, like transaction management, logging, messaging, and exposing POJO using one of the remote technologies like RMI, HTTP , web services, and so on.
  • Consistent abstraction layer, which provides integration with various standards like JPA (Java Persistence API), JDBC, JMS, and third party APIs like Hibernate, Top Link, JDO.
  • MVC framework, which provides a highly configurable Model View Controller implementation via strategy interfaces and accommodates numerous view technologies including JSP, Portlets, Velocity, Tiles, iText, and POI.implementation.

spring30-framework

Spring framework assists in POJO development where all the features described above can be applied to POJOs, and the Spring IoC container provides the necessary infrastructure to assemble POJOs to create required application. The following diagram as shown in the Figure 1 provides an overview of the various functionality offered by the Spring framework. Each of the functionality is provided by well defined Spring modules. Each of the functionality can be used independently to simplify some area of enterprise development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in above Figure 1. The functionality of each component is as follows:

  • The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.
  • Spring context: The Spring context module builds on the core module and 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 enterprise services functionality is provided through the specialized ApplicationContext object , which is an extension to BeanFactory.ApplicationContext is typically used by all applications as it provides various enteprise services.
  • Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework for managing application crosscutting concerns like transaction, logging, security and other concerns through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework.
  • Spring Transactions: The Spring transaction module provides support for declarative as well as programmatic transaction management that can be applied to Plain Old Java Objects (POJO). Spring Transaction module offers an abstraction for dealing with various transaction manager implementations like Hibernate, JTA, JDBC or application server specific transaction manager implementations like WebSphere or Weblogic. With this feature, your component can be decoupled from the specific API required by the corresponding transaction manager implementation.
  • Spring Persistence framework: Spring Persistence supports JDBC as well as integration with Object Relationship Mapper (ORM) frameworks. Spring JDBC module provides an abstraction layer which provides resource management and exception translation. The Spring JDBC module provides meaningful 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.The Spring ORM module plugs into several ORM frameworks to provide a consistent way to deal with Object Relational tools, including JDO, Hibernate, and iBatis SQL Maps as well as support for the standard Java Persistence API(JPA). All of these comply to Spring’s generic transaction and DAO exception hierarchies.
  • Spring Web: The Spring Web module builds on top of the context module, providing contexts for Web-based applications. The Spring web module provides framework for web integration and common functionality with other web frameworks can integrate with like Spring MVC and Spring portlet.
  • Spring presentation : The presentation framework is supported by Spring MVC framework module and Spring Portlet MVC framework module. The Spring Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, JSF, Struts, Velocity, Tiles, iText, and POI. The Spring Portlet MVC framework provides a MVC framework for creating portal based applications. The portlet MVC frameworks support the Java Portlet specification, which promote interoperability between various portlets containers.
  • Spring integration: The integration framework provides integration with popular technologies like Remoting (EJB, RMI, Spring Hessian, Burlap),JMS,Email,Web services and REST in a consistent manner.
  • Spring Test: Spring Test module supports the testing of Spring components with JUnit or TestNG.Since Spring promotes POJO based development, where all the functionality can be tested without the need for an external container, like EJB or Application Server.

Spring framework functionality can be used in any J2EE server and most of it also is adaptable to non-managed environments. A central focus of Spring is to allow for reusable business and data-access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (Web or EJB), standalone applications, test environments, and so on, without any hassle.

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components typically in a configuration file or using code metadata like Java annotations. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

For instance, take the following example of an online credit card enrollment account use case. For simplicity the online credit card enrollment use case carry out three steps, verifies the credit rating, links the customer account with credit card if credit rating is good and emails the user about the status of credit card (approved or rejected) . Each of these steps is implemented as Java classes i.e. CreditRating, CreditLinking and Email, respectively. Now in traditional application development without IOC, the following code snippet would be used by credit card application process as part of the createCreditCardAccount() method shown in Listing 1.

public void createCreditCardAccount(ICustomer icustomer) {

CreditRatingInterface creditRating = new CreditRating();

CreditLinkingInterface creditLinking = new CreditLinking();

EmailInterface email = Email();

boolean crediRating = creditRating.getUserCreditHistoryInformation(icustomer);

icustomer.setCreditRating(crediRating);

//Good Rating

if(crediRating) {

creditLinking.linkCreditBankAccount(icustomer); }

email.sendEmail(icustomer);

}

As you see in the above code, in the createCreditCardAccount() method we have created an instance of CreditRating, CreditLinking and Email object. Secondly if any of these objects would have dependency on other objects, the object would be needs instantiated in that scope (i.e. in that class or method). These dependencies can grow based on our application and manageability could become a difficult task. You may not realize that most of the time your object would be stateless and would eventually require one shared instance of object in your application, rather than creating a creating a new object for every request. Apart from object creation, you could also have configuration in your code i.e like looking up the Data source connection factory using JNDI.

Applying IOC principles would make your design modular and move out the object code creation code and configuration outside of the application code and manage these dependencies typically in some external configuration file. A container (like the Spring framework’s IOC container) is then responsible for creating the beans, managing the dependency and assembling the application from these loosely coupled beans. In the Spring IOC example section, you will look at how to apply IOC principles using Spring by taking the sample example of a Credit card enrollment use case that we had discussed above.

In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked. The three implementation pattern types for IOC are listed in the table below.

Type 1 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).
Type 2 Dependencies are assigned through JavaBeans properties (for example, setter methods).
Type 3 Dependencies are provided as constructor parameters and are not exposed as JavaBeans properties.

The Spring framework uses the Type 2 and Type 3 implementations for its IOC container.Spring framework support XML based configuration or Java annotations to manage bean configurations and dependency. For this example we would go with XML based configurations. Typically most of the applications uses XML based configurations. Java annotations support was added from Spring 2.5 release.

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

AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. 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. The advantage, of course, is that the Java class doesn’t need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled.

AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features.Spring provides its own AOP implementation through the Spring AOP module. For advanced AOP scenarios, Spring provides support for AspectJ. However, Spring AOP module should be sufficient in most common applicable scenarios.

The core of Spring’s design is the org.springframework.beans and org.springframework.context which provides Spring IOC implementation.The org.springframework.beans package typically isn’t used directly by users, but serves as the underlying medium for much of the other functionality. The next-highest layer of abstraction is the BeanFactory interface, an implementation of the Factory design pattern that enables objects to be created and retrieved by name. BeanFactory can also manage relationships between objects.

BeanFactory interface is typically not used by applications directly. The Spring IOC container implementation which is typically by applications is theApplicationContext interface which builds on top of the code BeanFactory.

The ApplicationContext concept is the foundation of Spring as an IOC container. IOC moves the responsibility for making things happen into the framework and away from application code. As I’ll show in the next examples, the Spring framework uses JavaBean properties and configuration data to figure out which dependencies must be set.

Because org.springframework.context.ApplicationContext is a simple interface it can be implemented for a range of underlying storage methods. The following is the example of FileSystemXmlApplicationContext which loads beans definitions files from the file system or from URLs in Listing 2.

ApplicationContext context = new
FileSystemXmlApplicationContext("mybean.xml");

Beans defined in XML files are lazily loaded, which means that the beans themselves will not be instantiated until they are needed. To retrieve a bean from ApplicationContext you can simply call the getBean() method passing in the name of the bean you want to retrieve, as shown in Listing 3.

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

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.

In this first article of the Spring Series article, I introduced you to the basics of the Spring framework. I started by discussing the functionality of Spring’s layered architecture and then offered a closer look at two of them: Spring AOP and the IOC container.

In next part , I will take a simple example and show you how the IOC pattern (as implemented by the Spring IOC container) works and how to inject dependencies, or services, into a working credit card account application rather than having to build them in from the ground up.

The Spring series articles was originally published in June 2005 by IBM DevelopeWorks. Based on the readers inputs, this article is now updated to latest 3.0.2 release.

“The Spring Series article was awarded the best article in the decade (2000 -2010) from IBM developerWorks and it generated 3x times views as compared to second best article , with highest number of ratings and feedback. Thank you readers for your comments, ratings and feedbacks for making this articles special”.

Tags : springSpring frameworkSpring series tutorial
Navveen

The author Navveen