Tag Archives: Spring Framework

Spring Book – Chapter 7 – Testing

Testing is an integral part of enterprise software development. It is one of the most important phases of the Software Development Lifecycle (SDLC) and has gained more importance in last decade or so. Having said that, there are many constraints either from framework level or project level, which makes testing effort in a project more challenging and time consuming. In this chapter we will first touch upon the importance of testing and see what are the various testing techniques employed in a typical application. Along the way we will see the problems imposed by various frameworks in achieving full test coverage.

After that we will see, how the Spring framework supports you in making your application more testable.

Why Testing Is Important?

As definition goes, testing is the practice of making objective judgments regarding the extent to which the system meets, exceeds or fails to meet stated objectives. Software Testing is the process used to help identify the correctness, completeness, security, and quality of developed computer software. Testing is a process of technical investigation, performed on behalf of stakeholders, that is intended to reveal quality-related information about the product with respect to the context in which it is intended to operate.

There are two fundamental purposes of testing; verifying specifications and managing risk.  First, testing is about verifying that what was specified is what was delivered. It verifies that the product meets the functional, performance, design, and implementation requirements identified in the specifications. Second, testing is about managing risk for both the acquiring organization and the system’s vendor/developer.

To find the importance of testing, you need to understand the goals of testing. Below are some of the important goals of testing:

  • Verify against a written and agreed specification
  • Assess quality of the software
  • Reveal failures if any in the delivered software
  • Verify contract such as legal, standards etc.
  • Learn how program works

TDD

Test-driven development (TDD) is an evolutionary approach to development which instructs you to have test-first development intent. You start by writing a test and then you code to elegantly fulfill the test requirements.

The steps in a typical TDD are shown in Figure 7-1 below. The first step is to quickly add or expand a unit test to your test suite. Next you run the test suite to ensure that the new test does in fact fail. You then update your functional code until it passes the test suite. Once the test suite does not fail, you should refactor the code; and then start over again.

Figure 7-1. TDD Steps

Refactoring – is a development practice for restructuring an existing code, altering its internal structure without changing its external behavior. Refactoring keeps the code clean and easy to understand.

Types of Testing

Tests can be grouped by where they are added in the software development process, or by the level of specificity of the test. The main levels during the development process are unit, integration, and system testing.

Unit Testing

Unit testing is a testing methodology employed to test a specific unit in an application. It does this verification process totally in isolation from other components. This testing has become so prominent that in some software development methodologies (Agile), the unit test cases have to be written before the actual class implantation which does the real work.

Unit tests must follow the FIRST Rules; these are Fast, Isolated, Repeatable, Self-Validated and Timely. Unit tests should be written in such a manner so as to test all the methods in the class along with all exception paths in the methods. The main aim of unit testing is to quickly test any new code or change to any existing code without spending much effort an time.

Though there are advantages, there are inherent limitations to this type of testing.  These don’t address the testing of the actual functional requirements of the application. These tests only cover testing of each module in the application. Also, we can’t test scenarios like asynchronous services which require configuring of JMS message queues inside the application server. Having said that, this is one of the testing types which is very important and can be used to test as much application functionality as possible.

Multiple unit test cases constitute to form a test suite. There are several open source products which allow the application team to setup and run these unit test cases. One of the well-known products is called JUnit. Being most popular, it has good integrations with other tools (Eclipse) and frameworks (Ant, Maven).

These types of tests are usually written by developers as they work on code to ensure that the specific intended function is working. Unit testing alone cannot verify the functionality of a piece of software, but rather is used to assure that the building blocks using which the software is built, work independently of each other.

Page Visitors: 5812

Spring Book – Chapter 6 – Enterprise Integration

Spring’s core support includes its capability of configuring application, enterprise integration, its testing capabilities and data access methodologies. In Chapter 4, I introduced you to various configuration styles available in Spring. In Chapter 5, I continued on to explain the various simplifications that you can do in your application. In this Chapter I will be covering enterprise integration which is one of the core support provided by the spring framework in detail.

I always like to call an application enterprise. For an application to be called enterprise, it needs to have enterprise components/objects on which it is built. I call an object enterprise when it has capability to handle transactions, capable of existing in a secured environment, has capability to integrate with other system, and so forth.

Using Spring framework, you can make simple POJOs getting transformed into what I call as enterprise objects, with minimal involvement of developers. Developers spend more time writing the actual business logic and the Spring container does all the magic behind the scenes.

Spring framework provides comprehensive infrastructural support for what we call an enterprise application. One such important component in any enterprise application is its capability to integrate. Spring handles plumbing involved in integrating various components in an enterprise application so that you can focus on actual business logic/business use case. Integrating enterprise application can be done in many ways. Each way has its own advantages and disadvantages. We will be discussing the various enterprise integration styles available in some detail in subsequent sections and will also cover the support rendered by Spring to achieve these integration styles in your enterprise application.

Integration Styles

Enterprise Application Integration (EAI) is an application of technology defined as the integration of data and services between applications. The patterns of modern day EAI are usually attributed to Enterprise Integration Patterns, by Gregor Hohpe, et. al., that categorizes and explains many of the integration patterns common to integration solutions. Hohpe, et. al., list four types of integration styles:

1. Shared Database: two systems query the same database for data to be passed. An example of this is when you have two EARs deployed whose entity classes (JPA, Hibernate, etc.) shared common tables for performing various business processes.

2. Remote Procedure Call: each of two systems expose services that the other can call. An example of this is EJB services, or SOAP and REST services.

3. Messaging: two systems connect to a common messaging system and exchange data and invoke behavior using messages. An example of this is the familiar hub-and-spoke JMS architecture.

4. File Transfer: two systems produce files whose payload is the message to be processed by the other system. An example of this is polling a directory or an FTP directory for a file and putting appropriate business logic and processing it.

These styles are disparate because no one solution will work all the time. According to requirement in your application, choose the right style which best fits your requirement. These architectural styles are different with each having its own unique advantages and disadvantages. The standards in JEE fall short to some extent and don’t provide complete solution when integration with other systems.

Shared Database

Integration between two systems can be as simple as joining two tables. Nevertheless, there arise several issues when you try to integrate two systems using this integration methodology. First of all it is difficult to come up with a single schema that will suit the needs of both the application and second is the creation of interdependencies between two systems having diverse requirements and mixing it could as good as mixing oil and water. That means it will never gel together in the ideal enterprise application as we think.

Having said that Shared database has its own advantages like it’s simple and transactional. Some of the disadvantages which can be attributed to this style of integration are that it could be slower and retard or obstruct the database schema evolution over a period of time with more and more features added onto the enterprise application due to changing business dynamics.

Figure 6-1. Shared Database Integration style

Spring framework provides extensive support for this integration style. The support by Spring for this integration style is as below:

  • Extensive support for transaction management
  • Ease of using JDBC using JdbcTemplate
  • Support for Object Relational Mapping (ORM)  integration
  • DataAccessException hierarchy makes exception handling easy
  • Spring Data, an umbrella project in the Spring framework

These will be explained to some extent in the following sections.

Transaction Management

Transaction management is critical in any form of applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the data is maintained.

Comprehensive transaction support is among the most convincing reasons for using the Spring framework. The Spring framework provides a consistent abstraction for transaction management that delivers various benefits. Some of which are:

  • Consistent programming model across different transaction APIs such as Java Transaction API (JTA), Java Database Connectivity (JDBC), Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO)
  • Declarative transaction management
  • Simpler API to code on
  • Excellent integration with Spring’s data access abstractions

We will be covering Spring’s support for managing transactions in Chapter 8, “Data Access” in detail. I just wanted to bring in this point here so that you will be able to link when we discuss this topic later in subsequent chapter.

Spring JDBC

Using conventional could be clumsy and not so clear way of doing things. Spring makes coding in JDBC easy and elegant using JdbcTemplate.

We will be covering Spring’s support for JDBC in Chapter 8, “Data Access” in detail.

Page Visitors: 2877

Spring Book – Chapter 5 – Application Configuration – Simplified

As we saw in Chapter 4, Spring provides three ways of configuring the container: XML, annotations, and last but not the least, Java configuration. The fact is, both XML and annotations have valid pros and cons. I am not saying that Java configuration is the answer to all the cons of both XML and annotations. I have given detailed pros and cons of each configuration styles in Chapter 4.

Configuration Styles – Pros and Cons

Just to re-state, pros of XML configuration can be:

  • Separation of concerns
  • Configurations kept outside the classes
  • Configuration easy to view
  • Configuration changeable without recompiling, etc.

Cons of XML style of configuration are:

  • Since XML is all string based, when used in the Java context, all these have to be converted to appropriate Java types, and this conversion could be painful and time consuming for the Java Virtual Machine.
  • Typos are very difficult to debug
  • Not type safe because of these strings

Pros of annotation-based configuration are:

  • Being Java it’s type safe, Spring does the configuring of its container in a speedy way
  • Indirect advantage being, it self-documents the class (open the class and you can see what is being injected by Spring)

Cons of annotation-based configuration are:

  • Cluttering of POJO’s
  • Any change requires change of application code
  • Any change requires recompilation and deployment

Pros of Java configuration are:

  • Being Java it’s type-safe, Spring does the configuring of its container in a speedy way
  • Clean separation of concerns
  • Single resource representing the application configuration
  • For systems which needs change constantly, configuration can change without changing the application code which is key for such systems.

Cons of Java configuration are:

  • Any change requires recompilation and deployment

Just by looking at the pros of Java configuration style, you can see that it includes the advantages provided by both XML and annotation type configuration. The only significant con to Java configuration is the requirement to recompile and redeploy if a change in configuration occurs.

In sum, Java is one of the best configuration styles that can be used in your application. However, we cannot just ignore other configuration styles. In this Chapter we will explore the different ways to simplify configuration so that we can mix and match various configuration styles in your application and make use of the advantages provided by all the various styles available with the Spring framework.

Bean definition inheritance

If multiple beans in your XML configuration scheme have certain features in common, you can use Java to create a parent bean, allowing your child bean to override some values or to add other values as needed. This way of using parent and child bean definitions can save a lot of time in addition to reducing your bean definition complexities. This can be called as a sort of templating pattern in Java.

Take an example class Employee as shown in the following example. We will be using this as the base class to explain the bean inheritance in detail.

[java]public class Employee{

private String name;

private String address;

private String designation;

//….

}[/java]

Inheritance with abstract

In the following example, parentEmployee bean cannot be instantiated as the class created is abstract in nature. This way you can make parentEmployee as a template and not allow others to instantiate it. If you try to instantiate parentEmployee bean you will get org.springframework.beans.factory.BeanIsAbstractException exception.

[xml]<bean id="parentEmployee" class="com.mybook.sample.Employee" abstract="true">

<property name="address" value="Dubai"/>

<property name="designation" value="STE"/>

</bean>

<bean id="childEmployee" parent="parentEmployee">

<property name="name" value="john"/>

<!– Here we are overriding the parent property namely designation–>

<property name="designation" value="SSE"/>

</bean>[/xml]

Page Visitors: 3744

Spring Book – Chapter 4 – Configuration Styles

In this Chapter, I will be explaining the various types of configuration styles that are available in Spring Framework to achieve Dependency Injection (DI). I will explain in detail the various configuration styles with working sample codes for clear understanding of each configuration styles. I will then give some best practices which can be followed to make your code maintainable and ways to avoid confusions and frustration to the developers as the application grows in size over a period of time.

Introduction to Spring Configuration Styles

Spring provides the following three ways of supplying metadata to the spring container to make the beans in your application ready to be used in your application as fully capable java objects:

  • XML
  • Annotations
  • Java

We can even mix and match the various ways of configurations in your application at will and spring doesn’t specify a particular way as best because it depends on the application that you are developing and the standards that your organization have already set. In the following sections, we will explore in detail the various configuration styles on which you could build your enterprise application.

History of Configuration Styles

Even though Spring allows developers to use any of the configuration styles currently available in your Spring application, it has supported various styles over a period of time, starting from the first version of Spring Framework, which was released in 2004. The history of configuration styles can be represented in tabular form as below:

Spring Version

Year

Configuration Style

Figure

Spring 1.0 2004 XML

Figure 4-1. XML Configuration

Spring 2.5 2007 Annotation

Figure 4-2. Annotation Configuration

Spring 3.0 2009 Java

Figure 4-3. Java Configuration

XML-based configuration

XML based configuration style was the first style based on which Spring Framework began its journey in the framework business. As the framework evolved over a period of time various alternatives to XML based configuration came and the framework accepted one by one configuration style gracefully. Spring uses dependency injection (DI) to achieve simplification and testability. (See Chapter 3 for detailed information about what DI is and the different forms of DI and their use.) However, the XML configuration files are verbose and unwieldy. They can become hard to read and manage when you are working on a large project where many Spring beans are defined. Simple XML based dependency injection in Spring is done shown in Listing 4-1:

Listing 4-1. XML based Dependency Injection in Spring

Lifecycle

Figure 4-4. XML based configuration lifecycle

Spring container loads the XML definitions according to the file locations supplied to the various ApplicationContext provided by Spring Framework. (The various ApplicationContext provided by Spring Framework are detailed in below section namely “Creating ApplicationContext”). Once this is done the BeanFactoryPostProcessor methods defined in the application are called. Soon after this, the actual bean instantiation and dependency injection happens. If BeanPostProcessor is defined, these are called as described in Chapter 3.

The following section provides an example of declaring/injecting various configurations using XML.

Injecting Scalar Values

Here in the below code snippet, “myString” and “32” are two scalar variables (member variables) in the class LoyaltyServiceImpl which need to be injected using the configuration.

Listing. Injection of Scalar variables in XML configuration

Corresponding Java code to the above XML configuration is:

Listing. Java Code for the above XML configuration

To show the example of bean configuration which requires injecting of lists and other collection types namely properties, Set and Map, I would like to use a class as below:

Listing. Class used to explain the injection of various types in XML configuration

Page Visitors: 4602

Spring Book – Chapter 3 – Spring Quick Start

In this chapter, we’ll see how Spring works and review its working principles. We’ll take a detailed look at bean definitions, accessing bean instances, and various bean scopes available in Spring Framework. The chapter also goes into detail about the Application Context lifecycle, with deep dives into the various phases of the lifecycle so that you understand the crux of Spring. Finally, because Dependency Injection is a very important concept in Spring, reducing code maintenance as well as increasing developer productivity, we provide a comprehensive discussion of this subject.

How Spring Works

The Spring container is at the core of Spring Framework. It creates the objects, wires them together, configures them, and manages their complete lifecycle from start (creation) to end (destruction). It uses dependency injection (DI) to manage the components that make up an enterprise application. Each object in the Spring container is called a Spring bean.

The Spring container gets its instructions by reading configuration metadata provided to it and, based on this, it decides what objects to instantiate, configure, and assemble. The configuration metadata can be provided to the container either by XML, Java annotations, or Java code. Weak-application POJO classes combined with the provided metadata instructions added to the Spring Container become powerful components in the enterprise application. Spring achieves all this by not locking down the application to any JEE-specific application servers. Figure 3-1 provides a high-level view of how Spring actually works in lay terms.

Figure 3-1. How Spring works

A Typical Application Requirement

A typical enterprise application consists of many components working together to achieve a business-problem solution. (In our sample application, various modules, such as Customer and Shipment, interact at various stages in an application to realize a business case. Implementing some changes in business dynamics will be cumbersome, however. (With Spring, you have a choice to swap the implementation with mere configurations.) As illustrated in Figure 3-2, each component might or might not interact with another, and as a whole, the enterprise application becomes monolithic in nature, with no way to separate the various components from the enterprise application if there is a change in business dynamics. It also becomes very hard to swap a component with a new implementation, which is a vital requirement in modern business dynamics and is an integral factor when architecting any enterprise application. Spring Framework tries to address these issues in an enterprise application in an easy way, without overhead, and it also reduces maintenance nightmares.

Figure 3-2. Various components in an application work together to actualize a business application.

Flaws

The main flaws in a typical enterprise application can be summarized as:

  • Parts (components) in an enterprise application find it difficult to search and integrate with other parts of the same application.
  • A part becomes obsolete because of changing business dynamics of an enterprise application, and it becomes hard to swap or change. This introduces maintenance nightmares and diminishes application agility.

Figure 3-3. A typical interaction between components in our sample application

As shown in Figure 3-3, components interact with one another in an enterprise application in a tightly coupled way, and any change in one component in the assembly point can adversely affect the other component and its behavior. As already mentioned, it also becomes very hard to swap one component with a similar or more sophisticated component, because of business changes/challenges. In the model shown in Figure 3-3, using Spring, at various stages of application, development components can be swapped according to your business needs. For example, if persisting logic changes—for example, moving away from conventional JDBC to Hibernate—you can easily swap the CustomerRepository with a new implementation based on Hibernate and replace it using the application configuration file of Spring container.

In a typical application development cycle, testing cannot be overlooked or ignored. Unit testing with the actual infrastructure might not be the right solution, however,  for the infrastructure aspect as well as for the time aspect. In this case, using Spring Framework, each component in the application can be swapped without any code changes to take in a new component implementation that doesn’t have dependency on the actual infrastructure but that does have dependency on a memory database, which is faster and more reliable for unit testing by developers. That is, using Spring, you can write a new implementation of any component, and the application can use these sample implementations by mere Spring configurations for doing the system testing. An easy and convenient way of testing is to use mocks. Spring out-of-box supports unit testing with JUnit and TestNG. Spring provides a separate set of classes to help you unit test your Spring classes. In Chapter 7, we cover testing of Spring applications in detail.

It’s a general conception that over a period of time, with growing complexity and size of the projects, JEE applications becomes more complex and unmanageable. Some of the reasons sttributed for this can be summarized as below:

  • JEE applications tend to contain excessive amounts of “plumbing” code which are unnecessary and unmanageable creating complexity and cluttering of code.
  • The EJB component model is generally considered to be unduly complex.
  • Compared to unit testing capability provided by other fraemworks available in the market, JEE applications are hard to unit test.

Spring to the Rescue

Spring works on the core principle of Inversion of Control (IoC). Using IoC, it tries to address the common issues that any enterprise application faces in the real world. It does this by taking the burden off the shoulders of the developers and allowing easy configurations of various components in an enterprise application. Developers always program to the interface, and Spring out-of-box gives support to creating and autowiring various instances needed by objects in a typical enterprise application.

Spring enables you to enjoy the key benefits of J2EE while minimizing the complexity encountered by application code. The essence of Spring is that it provides enterprise services to Plain Old Java Objects (POJOs). This is particularly valuable in a Java EE environment, but application code delivered as POJOs is naturally reusable in a variety of runtime environments.

Spring allows assembly of an application by using various components. These components have no trouble finding each other, and they can be easily swapped according to the business requirements. The components can be in POJOs and deployed in the Spring container, which in turn manages these objects, which in Spring Framework are called beans.

Page Visitors: 2573

Spring – Multiple transaction manager in an application

In the application context declare the following:-

In the Java code do the following as shown below as code snippet:-

Page Visitors: 4559

Spring Book – Chapter 2 – Getting started with Spring

Developing enterprise application using Spring Framework is much simpler than using standard Java EE in many ways. Even though Java EE’s declarative programming model using EJB simplifies infrastructural aspects of development such as transactions and security, t still introduces unwanted complexity to the application as a whole. Developers need to still write more Framework code than the application code. Over the period Java EE has also redefined itself to introduce new programming techniques like Aspect Oriented Programming (AOP) and Dependency Injection (DI). So many new Frameworks got evolved using these techniques. Leading from this pack of Framework at the moment is by Spring Framework by a long way. In this chapter I will try to give you details on various aspects of Spring Framework, along with the sample application that will be used throughout this book to show the various concepts in this Framework.

In this chapter, I will give you details on how you can start building applications with Spring Framework. I will also give details on the sample application on which the entire book is based. It also talks about the some basic concepts which are very much essential for understanding Spring in a holistic way.

Developing with Spring Framework

Getting the Spring Framework

Before you get started, you need to get the Spring Framework. You have two options to do so: you can either download the package distribution from Spring website, or you can checkout the source from github.

Downloading standard package distribution

Visit http://www.springsource.org/download/community?project=Spring%2520Framework and download the latest Spring release (version 3.1.1.RELEASE at the time of writing). Previous releases can also be found in this same page.

Checking out source from github

Alternatively you can visit https://github.com/SpringSource/spring-Framework and can download as required or fork the Framework and create your own repository and play around with it.

Using Maven Build Framework

If you are using Maven Build Framework for building your application, you can download the necessary artifacts into your project by mere declaring the maven repository in your build xml called as pom.xml. You will have to make sure that your machine is appropriately configured so that your Maven can look into the repository URL and download the necessary artifacts which you require in your project. Declare the repository as follows in your pom.xml:

Listing 1-1. Repository declaration in pom.xml if you are using maven as your build tool

After that declare the spring modules that you require in your project as below (in the below example spring-context jar with version 3.1.1.RELEASE will be downloaded into the project and set dependency on):

Spring Packaging

The Spring Framework is a series of JAR files, which we can get by two ways as explained in the above section. To install it all you really have to do is extract the downloaded compressed file to some location on your computer, and then reference the appropriate JARs in a Java project.

Spring Dependencies Structure

Quite simply the dependency between various jars comprising the Spring Framework can be summarized as below:

Figure 1 Spring Framework Dependencies

Page Visitors: 7782