Welcome!

Java Authors: Sandi Mappic, Bernard Golden, Lori MacVittie, Esmeralda Swartz, Trevor Parsons

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)

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.


@ThingsExpo Stories
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, 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. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at 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. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
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 Utimaco will exhibit at 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. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
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...
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...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

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 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.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
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...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, 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. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...