Chapter 16. EJB 3 and Spring

This chapter covers

  • Spring-enabled session beans
  • Injecting session beans into Spring POJOs
  • Using JPA with Spring

When the EJB portion of J2EE first came along, the industry flocked toward it. Imagine, an industry-wide specification for building distributed applications with layers and tiers and business logic! Prior to EJB 1’s attempt to do this, developers were constantly wrestling with two options, neither of which was ideal: use a proprietary vendor product or write your own. Both amounted to the same option; it’s just that in the second case the development team was the vendor with the one-of-a-kind solution. No matter how you looked at the domain, it meant vendor lock-in.

The road to EJB acceptance was not without challenges. The specification was vast and rigid, and placed a lot of constraints on developers and impacted how they built their applications. The industry wasn’t quite thrilled. EJB 2 went into development in an attempt to plug all the holes in EJB 1. Although EJB 2 did address many of the issues that plagued developers (such as defining more consistency in how vendors implemented the specification in order to make EJB applications more portable between vendor platforms), the programming model was still too verbose. It had become an all-or-nothing proposition for EJB 2. You either bought into the whole EJB 2/J2EE programming paradigm, or you didn’t buy into any of it. Architects found it difficult to design applications that only used parts of the specification. Enter the dawn of the lightweight Java application framework. (Cue eerie music...)

Sure, various pockets of the open source software (OSS) community had been working on these issues for a while—almost as soon as EJB 1 was released. Developers have a way of wanting to explore new avenues and solve hard problems; the application container crowd is no different. Apache did have some success with their Avalon[1] framework, which may be the most well known, but others wading into these waters discovered some useful principles for building lightweight containers. A couple of these are the Keel framework (www.keelframework.org) and the DNA framework (http://dna.codehaus.org). While there was interest in such lofty-minded goals, most of the industry viewed this commotion as fringe activity and ignored it until sometime around the middle of 2004, when Rod Johnson and a talented set of developers from Interface 21 began energetically promoting the Spring Framework (www.springframework.org).

1 This project is now closed; it’s no longer an active Apache project.

By now you may be looking up from this book and staring off into space, contemplating the question “What does Spring have to do with EJB 3?” Well, we’re glad you’re perceptive enough to ponder such matters, and we’ll see if we can answer that question by continuing with our little story.

Spring and EJB proponents haven’t always seen eye to eye. Spring adopters have more likely than not been burned by the weight of previous EJB specifications. In contrast, the EJB faithful have felt that the Spring folks have gone too far by moving away from an industry standard. This has created some fracturing in the Java community. Yet we still have to deal with the developer’s insatiable desire to explore, understand, and solve hard problems. Hmmm... where might this lead us?

We propose that this leads us to the reality that some in the Spring camp are interested in EJB 3. They would like to experiment with it, but they don’t want to leave their newfound comfort zone of the Spring container. The staunch EJB camp may also be intrigued by the whole Spring movement. After all, this movement is still growing; there has to be something to it, doesn’t there? Then there’s the third group: those who haven’t used Spring or EJB. Which way should they go?

In the spirit of OSS, we hope the reader views this chapter as the extension of an olive branch. Given the popularity of the Spring framework, we want to demonstrate that it is possible to peacefully coexist—to find the power in both options and use them effectively. We want to emphasize that EJB 3 is a specification and Spring is a framework. Although they are often characterized as two sides of the same coin, these two are not the same thing.

In this chapter you’ll learn how to use JPA entities and EJBs with Spring. We’ll also throw in some tips for using both EJB 3 and Spring in your applications, with examples that show both Spring 1.2 and 2.0 features. This chapter does not cover how to use Spring itself. For a thorough beginner-to-advanced treatment of Spring, be sure to check out Spring in Action (2nd edition) by Craig Walls and Ryan Breidenbach (Manning, 2007).

So what do you think? Are you ready to get EJB 3 and Spring working together?

16.1. Introducing the Spring framework

Simply put, Spring is an inversion of control (IoC) and AOP framework. While it is also a container, it is widely popular for its framework benefits. The Spring framework built on many of the lessons learned from the other projects, either directly or indirectly, by understanding the importance of certain principles now known as IoC and separation of concerns (SoC). The primary goal for the Spring framework is to simplify development of enterprise Java applications. In this section we’ll briefly introduce the Spring framework and then explore the IoC principle behind it.

16.1.1. Benefits of the Spring framework

Spring is one of the driving forces behind popularizing the POJO programming model and dependency injection. Enterprise application development with J2EE 1.4 and EJB 2 was very complex, and Spring gained popularity because it addressed many complexities and limitations of J2EE 1.4 and EJB 2. It provided a simple programming model for using resources such as JDBC or JMS or using popular persistence frameworks like Hibernate or TopLink by abstracting low-level API and configuration from developers without limiting developers’ choices.

Many developers want to choose a persistence, web, or messaging framework without having to do the integration work. The developers of the Spring framework realized that no matter which persistence, web, messaging, or “whatever” framework they selected to support, someone would want to use something else, and a better alternative would eventually come along. Also, this type of integration is typically expensive. By following the IoC and SoC principles, Spring was able to be both lightweight enough to let developers decide how much of the framework they needed, and flexible enough to support many permutations of competing component frameworks.

Spring provides several modules, such as the following:

  • AOP module
  • JDBC abstraction and DAO module
  • ORM integration module
  • Web module
  • MVC framework

Although the Spring framework supports almost as many features as a Java EE container, it is not positioned as an alternative to Java EE but as a framework that facilitates the development of applications with Java EE. That’s one of the primary reasons for Spring being successful as a framework. You can use the Spring framework on its own or inside a Java EE container. Most application servers, such as Oracle and WebLogic, provide additional support to use Spring.

Now let’s turn our focus to the IoC principle driving the Spring framework.

16.1.2. The inversion of control principle

Sometimes explained as the “Don’t Call Us, We’ll Call You” principle. It’s the idea that a component or service should do one thing, and do it well, and not have to know too much—if anything—about the other matters in the context of doing its job.

Let’s say you have a ThingAmaJig component that needs a WhatchaMaCallIt and a DooHickey in order to do its job. Now the ThingAmaJig can try to find the other two components when it’s invoked—or it could expect its caller to provide them. This second approach is the IoC principle.

Humans instinctively use IoC all the time and are not even aware of it. If you are at a client location and someone walks up to you and tells you that you have a call waiting from your coworker, they also hand you the phone that is already connected to your office, or tell you where the phone is. They don’t expect you to just “know” where your coworker was calling from, nor do they expect you to figure it out. They provide the needed information for you to complete the conversation.

The same is true for someone invited to speak at a conference. The speaker isn’t expected to provide the conference room, audience, refreshments, and so forth. Those are provided by someone else. However, these other components are critical to the speaker being able to perform the requested tasks—especially consuming the refreshments!

An article by Martin Fowler (www.martinfowler.com/articles/injection.html) proposed that while the IoC principle was good, its name could use a slight adjustment. He proposed dependency injection as a name that more accurately described what IoC did. It appears that most of the industry has agreed, and this is why you will see DI referenced more than IoC in newer literature, especially EJB 3 documentation.

16.1.3. The separation of concerns principle

For a component architecture to succeed in being both easy to use and flexible to extend, the ideas of interface and implementation need to be considered. The interface is the functional aspect describing what is to be done. The implementation is the specific how and what is to be accomplished.

This means that if you write a logging component and you would like to have the flexibility to log to a number of locations (database, file, socket, unknown, etc.) and support various protocols (HTTP, RMI, JINI, unknown, etc.), you have a design decision to make. You can try to guess which locations and protocols are the most popular, or you can write the log functionality in an interface, write a few implementations that use that interface, and encourage others to write any implementations that they may need.

The SoC idea is also sometimes referred to as the plug-in principle, which is more often how it is described. Spring allows separation of concerns with its rich support for aspect-oriented programming (AOP). It helps developers to focus on writing business logic without having to worry about system-level concerns such as performing transactions or logging in their code.

After looking more deeply into the principles Spring was built on, and with their new list of priorities for EJB 3 in hand, the EJB 3 Expert Group did several things to bring EJB 3 more in line with the goals being realized by Spring. These goals include POJO programming model, dependency injection, and use of interceptors.


Note

At the time of this writing, the Spring framework developers released Spring 2.0 with support for the EJB 3 JPA. It shipped TopLink Essentials as the default persistence provider. It is worth mentioning that Spring is adding partial support directly for EJB 3 as a part of Pitchfork project (www.interface21.com/pitchfork). This will enable you to use EJB 3 annotations such as @Stateless, @Interceptors, and @Resource in Spring beans.


Now that you have an idea what the Spring framework is, let’s explore how you can use Spring with JPA.

16.2. Using JPA with Spring

Spring has wide support for ORM technologies, including Hibernate, TopLink, and JDO. The approach Spring takes in how you use their framework makes coding to these ORM options and swapping between them very easy. Spring 2.0 extended this rich support for ORM technologies to include JPA. Table 16.1 shows the Java classes that developers are interested in for using EJB 3 JPA in Spring.

Table 16.1. Spring classes available for using JPA

Spring Class

Description

JpaTemplate

Simplifies JPA access code

JpaDaoSupport

Superclass for Spring DAOs for JPA data access

JpaTransactionManager

Used for transactional access of JPA

LocalEntityManagerFactoryBean

Factory that creates local entity manager when JPA is used outside Java EE

JpaDialect

Intended to use with a persistence provider outside Java EE

We’ll outline the steps for using the EJB 3 JPA from your web applications. We’ll assume you have some basic familiarity with Spring and that you are comfortable with entity packaging and EAOs.

We’ll primarily focus on using JpaDaoSupport and JpaTemplate, because they are intended to simplify the use of the EJB 3 JPA by shielding you from the details of the EntityManager API. We’ll assume you have experience with the general usage of the EntityManager API (which means you’ll appreciate even more how Spring is trying to simplify the EJB 3 JPA programming model).

Suppose that the ActionBazaar developers thought it would be cool to use Spring in their systems. They started creating a prototype to use Spring with JPA, and decided to implement a part of ActionBazaar in Spring as shown in figure 16.1.

Figure 16.1. This ActionBazaar bidding module uses Spring with JPA. The Spring bean employs an entity access object to access the entities using JpaTemplate.

We’ll work with the ActionBazaar bidding module shown in figure 16.1, in which a simple Spring EAO (BidSpringEAO) is used for accessing the ActionBazaar persistence unit using Spring’s JpaTemplate. We’ll create a Spring bean (BidService) and configure it to use the EAO. We’ll build an EAO that uses Spring’s JpaTemplate to manipulate entities and use the EAO in a Spring service bean. Finally, we’ll explore the Spring configuration that magically glues the EntityManager, EAO, and the Spring bean together.

16.2.1. Building JPA EAOs for Spring

In chapter 12 you learned that the Entity Access Object design pattern improves code maintainability by decoupling the persistence logic from the business logic. Spring provides EAO (Spring still calls it DAO) for JPA and many O/R mapping frameworks such as Hibernate and TopLink.

Spring provides two ways to access and manipulate entities in building Spring EAOs: using the JPA API directly or using JpaTemplate. In chapter 12 we used EAOs to call the EntityManager API directly. We’ll now demonstrate how to change the implementation classes to use JPA from Spring applications with the Spring JpaTemplate. Listing 16.1 shows the ActionBazaar EAO implementation classes you need when using JPA from Spring applications. Note that the Spring classnames continue to use the DAO naming convention instead of the revised EAO naming that we’re featuring in this book.

Listing 16.1. EAO implementation when using JPA from Spring applications

The class that implements the EAO interface must extend JpaDaoSupport . Instead of using the EntityManager API, you use JpaTemplate. In listing 16.1, we’ve used the persist and merge methods and to persist or merge entity instances.

Using JpaTemplate

How are exceptions handled with regard to JpaTemplate? We’re glad you asked. You need to be aware that JpaTemplate does not throw any persistence API exceptions. Instead, it throws Spring’s DataAccessException. The primary benefit of this to developers is that by translating exceptions into those provided by the Spring framework, the persistence mechanism is neutral. This means you can swap out persistence mechanisms and your application code won’t have to change to support the new framework’s error handling. This makes it easier to migrate from one persistence toolkit to another, or to support multiple toolkits if you are a tool vendor. Table 16.2 describes some of the important methods in JpaTemplate.

Table 16.2. Important JpaTemplate methods provided by Spring

JpaTemplate Methods

Description

persist(Object entity)

Persists an entity instance

remove(Object entity)

Removes an entity instance

merge(T entity)

Merges a detached entity instance

refresh(Object entity)

Refreshes an entity instance from the database

<T> T find(Class<T> entityClass,Object Id)

Retrieves an entity instance by primary key

List find(String queryString)

Retrieves a list of entities using a dynamic query

List find(String queryString, Object values)

Restricts a list of entities using a dynamic query with positional parameters

findByNamedQuery(String queryName)

Retrieves a list of entities using a named query

findByNamedQuery(String queryName, Map<String,Object> params)

Retrieves a list of entities using a named query with named parameters

You can use the JpaTemplate methods to access entities. Spring limits some of the repetitive use of the EJB 3 JPA. For example, if you want to you use a dynamic query to retrieve all Bidders with Gold status, then JpaTemplate will yield the following:

List bidders = getJpaTemplate().find(
"SELECT b FROM Bidder b WHERE status = ?1", "Gold");

The equivalent code with the EntityManager API will look like this:

List bidders = em.createQuery(
"SELECT b FROM Bidder b WHERE status = ?1")
.setParameter(1, "Gold")
.getResultList();

This code makes it evident that Spring makes using the EJB 3 JPA simpler. We encourage you to explore other JpaTemplate methods.

The only problem we see with JpaTemplate is that it does not provide fine-grained access to the EntityManager API’s methods.

JPA EAO in your service beans

Spring’s service beans are similar to the EJB 3 session beans that you work with to implement business logic. In our example the BidServiceBean is used to place a bid on an item, and it uses the EAOs to manipulate the entities. You can use the EAOs in your service classes, and the EAOs can be injected into the POJOs with Spring’s setter injection as follows:

public class BidServiceBean implements BidService  {

protected ItemEAO itemEAO;
protected BidEAO bidEAO ;

public BidServiceBean() {
}

//Inject Instances of Item and BidEAO
public void setItemEAO(ItemEAO itemEAO) {
this.itemEAO = itemEAO;
}

public void setBidEAO(BidEAO ) {
this.bidEAO = bidEAO;
}

public Long addBid(String userId, Long itemId, Double bidPrice) {
...
}
}

The BidServiceBean class looks similar to the PlaceBidBean class—the only remarkable difference is that it is a POJO with no annotations, JNDI lookup, or use of EAO factory code of any kind.

If you are new to Spring, you must be wondering, “If all classes are POJOs, then how does the framework know about the EntityManager, and how does it inject instances of EntityManager?” It’s all based on a little Spring configuration magic, which we dive into next.

16.2.2. Configuring Spring to use the JPA

The real power of Spring comes from how it configures services via dependency injection. For our example this means you need to configure the EntityManagerFactory. To coax ActionBazaar to work with Spring, you’ll need the configuration shown in listing 16.2.

Listing 16.2. Spring configuration to use JPA

Even if you’re not familiar with Spring, you can probably figure out what’s going on in this configuration file (actionBazaar-service.xml). The first bean instance, entityManager, injects an instance of the EntityManager by retrieving it from the JNDI namespace when it is referenced from another bean instance. The next bean, bidEAO, asks Spring to automatically wire it to use the previous entityManager. The final bean, bidService, requests that Spring inject the bidEAO bean as the implementation for it to use at runtime.

Configuring Spring to use the EntityManager

Because Spring is a lightweight container, it can work either inside a Java EE container or independently. Spring can use a container- or an application-managed EntityManager either inside or outside the container. While you’re using Spring within a Java EE container, it acts as a proxy between the container and the application and injects an EntityManager or EntityManagerFactory when your application needs it. That way, you don’t have to worry about including extra JPA code.

In this chapter we primarily focus on Spring as a framework within the Java EE container. This means you have to configure Spring so it can retrieve an EntityManager from the Java EE container and inject an instance of an EntityManager whenever you use a JpaTemplate. If you’re using Spring within a Java EE 5 container, you must use either the JndiObjectFactoryBean or Spring 2.0’s new jee:jndi-lookup mechanism to wire an instance of EntityManager (as we did in listing 16.2). If you want the new Spring 2.0 configuration instead of JndiObjectFactoryBean, then use this configuration:

<jee:jndi-lookup id = "entityManager"
jndi-name = "actionBazaar"
resource-ref = "true"/>

Remember, this notation works only if you’ve upgraded to version 2 of Spring.

Using Spring outside Java EE container with JPA

As we discussed earlier, Spring 2.0 acts as a container and supports the container-managed EntityManager with JPA. The Spring container manages the persistence unit. You have to use LocalContainerEntityManagerFactoryBean to wire an entityManagerFactory. The LocalContainerEntityManagerFactoryBean reads the persistence.xml packaged in the application to configure the persistence unit by using the data source supplied. It can also perform load-time weaving to search for annotated entity classes. Here is an example configuration of the container-managed EntityManager:

<beans>
<bean id = "entityManagerFactory"
class = "org.springframework.orm.jpa.
LocalContainerEntityManagerFactoryBean">
...
<property name = "loadTimeWeaver">
<bean class = "org.springframework.instrument.classloading.
SimpleLoadTimeWeaver"/>
</property>
</bean>
<bean id = "bidEAO"
class = "actionbazaar.persistence.eao.BidSpringEAO"
autowire = "byType">
<property name = "entityManagerFactory"
ref = "entityManagerFactory"/>
</bean>
</beans>

For more information, refer to the Spring documentation.

If you’re using Spring outside a Java EE container, you can use a LocalEntityManagerFactory and your configuration will look like this:

<bean id = "entityManagerFactory"
class = "org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
...
</bean>

This, of course, demonstrates that JPA can work independently of both a Java EE container and EJB 3.

Wiring entity access objects

The EAOs use JpaTemplate, so we need to wire the EAOs to use JpaTemplate’s methods. The EAOs are wired in the Spring configuration as in listing 16.2. If you recall, the EAOs extend the org.springframework.orm.jpa.support.JpaDaoSupport and it has a dependency on EntityManager; therefore, we need to inject an instance of EntityManager. Spring’s autowire-by-type mechanism indicates to the Spring container that it should find a single instance of a Spring bean that matches the property being wired. In this case, the EAO class uses the entityManager property to obtain an instance of EntityManager that we defined earlier in listing 16.2. You must pass EntityManager as a property to the EAO as follows:

<property name = "entityManager" ref = "entityManager"/>

At runtime Spring will take care of creating the entityManager and injecting it into the EAO.

If you’re using an application-managed entity manager or using Spring with JPA outside the container, you have to wire the entityManageFactory property instead of an entityManager as follows:

<bean id = "bidEAO"
class = "actionbazaar.persistence.eao.BidSpringEAO"
autowire = "byType">
<property name = "entityManagerFactory"
ref = "entityManagerFactory"/>
</bean>
Wiring service beans

Your web applications use service beans to access entities from the presentation tier. You simply wire your service beans (as in listing 16.2) in the Spring configuration file to have them injected. Some steps can be quite mechanical, and are required for every EAO and service bean.

Appropriately configuring Spring for your server allows you to deploy the application using Spring, proving again that you can use JPA outside of a Java EE container.

Let’s now examine how you unite the power of Spring and EJB 3 components (session beans and MDBs).

16.3. Combining the power of EJB 3 and Spring

In addition to using JPA with Spring, you may combine the flexibility of Spring beans with the power of EJB 3 in your applications. You have two options. You can use the power of Spring—POJO injection, AOP features, etc.—by developing Spring-enabled EJB applications, or you can invoke an EJB from a Spring bean. At the time of this writing, Spring 2.0 has no documented support for EJB 3 session beans, but we found some ways to make EJB 3 beans work with Spring beans and in this section we’ll reveal our discoveries.

In this section you’ll see two ways you can combine power of EJB 3 components and Spring beans. First you’ll learn about using Spring from EJB 3 components; then we’ll show you how to access an EJB 3 session bean from a Spring bean.

16.3.1. Developing Spring-enabled EJBs

Let’s say you want to use declarative transactions, timers, security, and the web services features of EJB in your applications, but you also want to leverage the POJO injection, AOP, and JpaTemplate features of Spring 2.0. Spring provides several support classes, listed in table 16.3, that you can use to integrate EJBs. Note that these are the classes provided for use with EJB 2, and we expect there will be several changes in these classes to be used with EJB 3. However, you can still use these abstract classes with EJB 3 beans.

Table 16.3. Spring support classes for building Spring-enabled EJBs

Support Class

Purpose

AbstractStatelessSessionBean

Used for Spring-enabled stateless session beans

AbstractStatefulSessionBean

Used for Spring-enabled stateful session beans

AbstractJMSMessageDrivenBean

Used for Spring-enabled JMS message-driven beans

AbstractMessageDrivenBean

Used for Spring-enabled connector-based MDBs

The abstract classes provide access to the Spring bean factory, and you have to implement the onEjbCreate method in your EJB class to retrieve a Spring bean.

In ActionBazaar we want to use Spring with session beans. This means that the BidServiceBean we developed in section 16.1 is used by the PlaceBid EJB, as shown in figure 16.2.

Figure 16.2. You can combine the power of Spring and EJB 3 by developing a Spring-enabled session bean. You can use the declarative transaction, security, and web services features of EJB 3 with the POJO injection and JpaTemplate features of Spring.

The BidServiceBean is defined as a Spring bean using a Spring configuration file named actionBazaar-service.xml as follows:

<beans>
...
<bean id = "bidService" class =
"actionbazaar.buslogic.BidServiceBean">
</bean>
...
</beans>

When an EJB instance is created, a Spring bean factory is automatically created and is made available to the EJB. While using this approach, you typically use the EJB as a façade and delegate the task to Spring beans.

Listing 16.3 shows the PlaceBid EJB developed as a Spring-enabled stateless session bean. In this example, the PlaceBid EJB acts as a façade and delegates the actual business logic to the BidServiceBean.

Listing 16.3. Spring-enabled stateless PlaceBid EJB

In listing 16.3 the bean class extends the Spring support class in the (org.springframework.ejb.support.AbstractStatelessSessionBean) package . Note that the EJB bean cannot inherit from another bean or class because Java does not support multiple inheritances.

The BidServiceBean POJO is defined as an instance variable . When a PlaceBid EJB instance is created, the onEjbCreate method is invoked and an instance of BidServiceBean is retrieved and stored in the POJO that we defined . The business method delegates the task to the BidServiceBean when it is invoked .

Now you must be wondering how the Spring bean factory is created and how the Spring configuration is provided. Under the covers, when an EJB instance is created it performs a JNDI lookup to locate the path (java:comp/env/ejb/BeanFactoryPath) for the bean factory. Therefore, you have to define the following environment variable in the EJB deployment descriptor for the EJB:

<session>
<display-name>PlaceBid</display-name>
<ejb-name>PlaceBid</ejb-name>
<env-entry>
<env-entry-name>ejb/BeanFactoryPath</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>/actionBazaar-service.xml</env-entry-value>
</env-entry>
</session>

The env-entry-value for the ejb/BeanFactoryPath environment variable is set to /actionBazaar-service.xml.

After you package the EJB and Spring configuration file, you should be able to invoke the EJB, and internally it will use Spring beans to perform the intended task.

16.3.2. Using session beans from Spring beans

Perhaps by now you’ve grown fond of EJB 3 and worked with it in your application. Some of your other application modules happen to use Spring. What you’d like to do is reuse the business logic you’ve developed in your EJBs by incorporating it into your Spring component, as shown in figure 16.3. In this section we’ll show you how to inject instances of session beans into your Spring beans.

Figure 16.3. You can access a session bean from a Spring bean and reuse the business logic.

Suupose you have a session bean named ItemManager:

@Stateless(name = "ItemManager")
public class ItemManagerBean implements ItemManager {
public Item addItem(String title, String description,
Double initialPrice, String sellerId) {
...
return item;
}
}

You want to use the ItemManager session bean in the ItemServiceBean, which is a Spring POJO (see listing 16.4).

Listing 16.4. A Spring POJO that uses an injected stateless session bean

In listing 16.4 you will see no difference in using a POJO because EJB 3 session beans are also POJOs. In the Spring bean, we’ve defined an instance variable for the EJB interface ItemManager and we use setter injection to inject an instance of the EJB object and invoke a method on the EJB .

You must be wondering where the actual magic happens. We aren’t doing a JNDI lookup, and we’re not using the @EJB annotation to inject an EJB object. The real magic occurs in wiring the EJB in the Spring configuration, as shown in listing 16.5. Spring has factory classes for wiring invocation of EJB 2.1 session beans. Fortunately, you don’t need those and you can use the JndiObjectFactoryBean.

Listing 16.5. A Spring POJO that uses an injected stateless session bean

In listing 16.5 we define a bean instance that injects an EJB instance by looking it up in the JNDI when referenced by another bean instance .

If you are a big fan of the new Spring 2.0 configuration, then you’ll be tempted to use the following instead of JndiObjectFactoryBean. Go ahead; indulge your temptation.

<jee:jndi-lookup id = "itemManager"
jndi-name = "ejb/ItemManager"
resource-ref = "true"/>

Unlike in EJB 2, there is no difference between invoking remote or local EJBs in EJB 3, and the configuration will be identical for both local and remote session beans.

We encourage you to explore the latest Spring 2.0 documentation at www.springframework.org/documentation to learn about the latest support of EJB 3 features in the Spring framework.

16.4. Summary

This chapter explained that even though EJB 3 is a specification and Spring is a framework, you can use them together successfully to build flexible, powerful applications. You can use parts of the EJB 3 implementation, or all of it, within your Spring applications. Spring can simplify the use of both EJB 3 and JPA, but at the price of foraging through Spring’s XML configuration files. You learned how to develop a Spring-enabled EJB (session bean or MDB) and leverage the power of Spring within your EJB components. Similarly, you can access an EJB 3 session bean from your Spring bean and reuse your business logic.

EJB 3 is a great framework for building enterprise Java applications, and it significantly improves developer productivity. It has some minor limitations, such as support for POJO injection, and we hope that these limitations will be addressed in the next version of the specification. Throughout this book we provided many best practices and tuning tips, and we trust you can use this information to effectively build your next application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset