Daily Archives: July 8, 2013

Spring Book – Chapter 8 – Data Access

One of the very important aspect in any enterprise application is the ability to get data in and out of your application with ease. Thinking on the same lines, Spring framework provides extensive support for data access. In this Chapter we will first explore the various data access technologies and then see the support provided by Spring for using these technologies in your application.

Spring effectively makes data access easier by managing the various resource for you, by providing abstraction and easy API helpers and by supporting all major data access technologies available in the industry so that you don’t have to get yourself bogged down to a particular technology. Going along with the Spring philosophy it lets your Spring application integrate to any data access technology with ease.

In this Chapter we will see the support given the Spring framework in interacting between data access layer and the service layer in your application. Spring compressive support for transaction management will be covered briefly as we have dedicated Chapter 9 for this specific topic. In this chapter we will also be covering various data access frameworks and technologies which the Spring framework integrates with almost ease.

Enterprise Data Access

Spring integrates and works just fine with all leading data access technologies at present available in market. Accessing eternal system like a database requires various resources at various stages. You will also have to look for resource contention and make sure that resource which is limited is managed properly and efficiently. Such resource management becomes critically important in mission critical enterprise application.

Putting the burden of maintaining these resources in an application to a developer not only puts additional pressure in a developer but also puts an additional risk on the overall application’s success. Spring provides comprehensive resource management capability which takes this burden away from the developer and entrust him with writing the actual business application logic.

Resource Management

As discussed earlier Spring integrates seamlessly with almost all data access technologies like JDBC, Hibernate, iBatis, JPA or JDO in a consistent way. Using Spring, you are not locked down to a particular technology and as case may be, you have the freedom of switching between the various technologies without worrying too much about the technology specific nitty-gritties. Figure 8-1 also shows the various classes which will be used to in the code samples in this chapter in various sections.

Figure 8-1. Spring Integration with well know data access technologies

Spring internally take care of the various resource management functionalities specific to data access technologies so that the developer concentrates on the actual application logic rather than data access technology specific coding.

Some of the key features which the Spring framework provides in resource management are:

  • Transaction Management
  • Connection Management
  • Exception Handling

In a typical application, the resource management capabilities are related with connection and transaction management. While trying to manage connection and transaction, there are exceptions that arise and resource management should also be capable of dealing these exceptions in timely and orderly fashion. Figure 8-2 shows a typical resource management scenario in an application.

Figure 8-2. A typical resource management scenario in any application

The following sections will look into these features of Spring in some detail so that you get a clear picture of what are the features which Spring transparently does for you in developing your application.

Page Visitors: 10635

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: 5833

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: 2883

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: 3753