Welcome!

Java Authors: Paige Leidig, Carmen Gonzalez, Trevor Parsons, Pat Romanski, Roger Strukhoff

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.

@ThingsExpo Stories
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.
SYS-CON Events announced today that Gigaom Research has been named "Media Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Ashar Baig, Research Director, Cloud, at Gigaom Research, will also lead a Power Panel on the topic "Choosing the Right Cloud Option." Gigaom Research provides timely, in-depth analysis of emerging technologies for individual and corporate subscribers. Gigaom Research's network of 200+ independent analysts provides new content daily that bridges the gap between break...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
Swiss innovators dizmo Inc. launches its ground-breaking software, which turns any digital surface into an immersive platform. The dizmo platform seamlessly connects digital and physical objects in the home and at the workplace. Dizmo breaks down traditional boundaries between device, operating systems, apps and software, transforming the way users work, play and live. It supports orchestration and collaboration in an unparalleled way enabling any data to instantaneously be accessed on any surface, anywhere and made interactive. Dizmo brings fantasies as seen in Sci-fi movies such as Iro...
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, will describe an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people’s real needs and desires.
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...