Welcome!

Java Authors: Elizabeth White, Liz McMillan, Kevin Benedict, Greg Akers, Patrick Carey

Related Topics: Java, Websphere

Java: Article

Cover Story: What Is POJO Programming?

Introducing POJO application development

The novel A Deepness in the Sky by Vernor Vinge is set in the distant future. The character Pham Nuwen is responsible for maintaining software whose components are thousands of years old. Today, however, it's difficult to imagine maintaining an Enterprise Java application for more than a few years. More often than not, the application is tightly coupled to infrastructure frameworks that evolve rapidly in ways that don't preserve backwards compatibility. Consequently, upgrading to a new and improved framework can be challenging and risky.

Fortunately, there's now a much better way to build Enterprise Java applications: Plain Old Java Objects (POJOs), which are classes that don't implement infrastructure framework-specific interfaces, and non-invasive frameworks such as Spring, Hibernate, JDO, and EJB 3, which provide services for POJOs.

Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code. And, as an added bonus, you can often deploy a POJO application using a simpler, Web container-only application server.

In this article, you'll learn about POJO programming. I'll begin by describing the concept of POJOs. You'll then get an overview of persisting POJOs with Hibernate and EJB 3 and making them transactional with EJB 3 and Spring. Of course, it's unlikely that the applications we're developing today will be used thousands of years from now but until their demise, using POJOs will make it easier to upgrade them to use newer frameworks.

What Is a POJO?
Even though it has tremendous benefits, the concept of a POJO is remarkably simple. A POJO is a Java object that doesn't implement any special interfaces such as those defined by the EJB 2 framework. Martin Fowler, Rebbecca Parsons, and Josh MacKenzie coined the name to give regular Java objects an exciting-sounding name that encouraged developers to use them (www.martinfowler.com/bliki/POJO.html).

To contrast the EJB and POJO approaches consider the following example. Imagine that you worked for a bank and needed to implement a service to transfer money from one bank account to another. If you were using EJB2, your code would most likely consist of a MoneyTransferService stateless session bean that coordinated the transfer of money between the accounts and an Account entity bean that accessed the account data. The problem with this design is that each EJB would be a mixture of business logic and EJB 2 infrastructure code. They would be intimately coupled to the EJB 2 framework. Furthermore, they would be difficult to test without deploying unless you jumped through the kinds of hoops described in TwoLevelDomain (www.theserverside.com/articles/article.tss?l=TwoLevelDomainModel).

By comparison, the POJO version (which is downloadable from www.pojosinaction.com) would look something like Listing 1. The MoneyTransferService and its implementation class define a transfer() method and the Account class maintains a balance and defines debit() and credit() methods. The AccountDAO is the interface for the Data Access Object (DAO) class whose implementation I'll describe later.

As you can see, these are regular Java classes. None of them implement special interfaces or call any framework classes. What's more, the MoneyTransferService doesn't instantiate the AccountDAO directly or look it up using an API such as JNDI. Instead, the AccountDAO is passed as a constructor parameter. This is an example of what is termed dependency injection, which is one of the key enablers for POJO development (www.martinfowler.com/articles/injection.html). In this example, dependency injection decouples the MoneyTransferService from the infrastructure framework. The MoneyTransferService only depends on the AccountDAO interface - not on the framework used to implement the AccountDAO or an API such as JNDI.

You could, of course, simplify the MoneyTransferService by dispensing with the AccountDAO and directly injecting, for example, a Spring HibernateTemplate or an EJB 3 EntityManager. However, I generally prefer to keep my framework-specific data access code separate from my business logic.

The Benefits of POJOs
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. They also simplify development because rather than being forced to think about everything - business logic, persistence, transactions, etc. - at once, you can focus instead on one thing at a time. You can design and implement the business logic and then, once that's working, you can deal with persistence and transactions.

POJOs also accelerate development. You can test your business logic outside of the application server and without a database. You don't have to package your code and deploy it in the application server. You also don't have to keep the database schema constantly in sync with the object model or spend time waiting for slow-running database tests to finish. Tests run in a few seconds and development can happen at the speed of thought - or at least as fast as you can type!

But by now you probably have questions such as what about transactions? Security? Persistence? Remoting? And how do you assemble an application with dependency injection? As you might have guessed, POJOs by themselves are insufficient. To use them in an enterprise application you have to use one or more frameworks.

Overview of Frameworks for POJOs
When developing an enterprise application, you need services such as transaction management, security, and persistence. You also need a way to assemble components together and access enterprise resources such as JDBC DataSources. One option is to use some very popular non-EJB frameworks such as Hibernate, JDO, and Spring. The Hibernate and JDO frameworks provide persistence for POJOs. The Spring framework provides services for POJOs such as transaction management and dependency injection. It also has support for POJO remoting and is the foundation of the Acegi Security framework (http://acegisecurity.sourceforge.net) that provides security for POJOs. One big of advantage of not using the EJB container is that you can sometimes deploy your POJO application in a simple (and sometimes cheaper) Web container-only server.

Another option is to use the emerging EJB 3 standard, which has adopted many POJO concepts and is a big improvement over EJB 2. In EJB 3, EJBs are very POJO-like in not implementing any special interfaces. Furthermore, EJB 3 entity beans are intended to be the standard persistence mechanism for Java and work both inside and outside the EJB container.

One important benefit of EJB 3, Spring, Hibernate, and JDO is that they are non-invasive. Unlike older technologies such as EJB2, they provide services such as transactions and persistence without requiring the application classes to implement any special interfaces. Moreover, only a small fraction of your code must call any APIs. Classes can be transactional or persistent while still being POJOs.

To use the services provided by these frameworks you must write metadata that configures the frameworks. The metadata comes in the form of either Java 5 annotations or XML configuration files. Later in this article, I'll provide examples of how you use this metadata to map POJOs to a relational database and make them transactions.

Now that you have had an overview of POJOs and their associated frameworks, let's look at dependency injection, persistence, and transaction management in more detail.

Injecting Dependencies into POJOs
Earlier we saw how the AccountDAO was passed as a constructor parameter to the MoneyTransferService. This kind of dependency injection is called constructor injection. Another kind of dependency injection is setter injection and consists of passing dependencies as setter parameters. The third kind of dependency injection is field injection and involves initializing fields directly. I prefer to use constructor injection because it ensures that an object is constructed with the required dependencies but setter and field injection are also useful.

Dependency injection has the following benefits:

  • Simpler code - It eliminates the need to call lookup APIs. Because a component's dependencies are passed to it you no longer have to write tedious JNDI code to look up a dependency.
  • Decouples application components from one another and the infrastructure framework - Dependency injection lets you construct an application from loosely coupled components. Components depend mainly on interfaces rather than on concrete implementations. There are no calls to framework-specific lookup code. The dependencies on the infrastructure frameworks are localized to only those components that call them directly such as DAO implementations.
  • Easier testing - You can test components in isolation by injecting mock implementations. For example, we can write tests for the MoneyTransferService that use a mock implementation of the AccountDAO. These kinds of tests are essential if you want to be able to work on your business logic without worrying about persistence. They also run a lot faster than those that access a database.
There has to be some application start-up code that instantiates the components and wires them together. You could write the start-up code yourself. For example, you could write some code that creates an instance of a class that implements AccountDAO and then passes it to an instance of the MoneyTransferServiceImpl. However, in a typical application it's usually more convenient to let Spring or EJB 3 inject the dependencies for you.

Spring Dependency Injection
Dependency injection is one of the core features of the Spring framework. To use it, you must configure Spring's bean factory, which is a sophisticated factory that instantiates objects and wires them together using either constructor injection or setter injection. Here's an example of how to do that:

<bean name="moneyTransferService" class="... MoneyTransferServiceImpl">
    <constructor-arg ref="accountDAO"/>
</bean>

<bean name="accountDAO" class="... AccountDAOHibernateImpl">
...
</bean>

More Stories By Christopher Richardson

Chris Richardson is the author of the recently published POJOs in Action. He's a developer, architect, and mentor with over 20 years of experience. Chris runs a consulting company that jumpstarts new development projects and helps teams that are frustrated with Enterprise Java to become more productive and successful. He lives in Oakland, CA with his wife and three children.

Comments (8) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Preet 06/24/08 01:42:08 PM EDT

interesting read... answers the what, but, and what ifs..
Thanks! I am newbie in this domain and this is exactly what I was looking for.

Mathan 02/26/08 10:39:21 AM EST

The main advantage of the POJOs are felt in distributed applications. Assume that your application is consuming services from 10 different applications. If one of them is down, then your application is effectively down. Instead, if you have the POJOs for all those apps bundled in your app, then your application can stand alone without any dependency

rogerv 03/28/06 05:20:31 PM EST

What Is POJO Programming?

Oh - that's where you write 30% of a Java application in a declarative, XML-based domain specific language.

For all practical purposes (and by very definition) the domain specific language will be unique to a given POJO container and hence will render the Java application essentially unportable.

Patrick Ellul 03/14/06 10:25:04 PM EST

I found this article very helpful with introducing me to the concepts behind POJO's and ORM's and frameworks such as Spring and Hibernate.

Justin Peck 03/13/06 12:28:09 AM EST

I liked this article so much, I wrote a Web application after having read it. Spring really does make programming Java-base Web apps fun again. Thanks for the article!

[You can see the app now at http://javajuster.com]

Alain Ah Ming 02/26/06 05:21:30 AM EST

Is this simply replacing the underlying entity EJB with the value object?
If a J2EE app were designed in a way that we had distinct segregation as follows:
Session EJB --> BusinessLogic Helper class --ValueObj--> DAO interface --ValueObj--> DAO impl class --ValueObj--> Entity EJB

would that would make it as good as what POJO prog is trying to achieve?

From our test class, we can easily invoke our business logic helper class (which is a pure POJO) by injecting a test DAO impl class.
That effectively leaves out any dependency to the underlying framework (EJB or spring).

harris reynolds 02/23/06 05:39:06 PM EST

Trackback Added: JDJ RIP; I receive several trade rags about technolgy. Most of them get stacked up in a pile by my desk that I eventually go through after they start cluttering the office. When going through the latest round of magazines recently I...

SYS-CON Italy News Desk 02/21/06 01:40:28 PM EST

The novel A Deepness in the Sky by Vernor Vinge is set in the distant future. The character Pham Nuwen is responsible for maintaining software whose components are thousands of years old. Today, however, it's difficult to imagine maintaining an Enterprise Java application for more than a few years. More often than not, the application is tightly coupled to infrastructure frameworks that evolve rapidly in ways that don't preserve backwards compatibility. Consequently, upgrading to a new and improved framework can be challenging and risky.