/
SAMPLE CHAPTER SAMPLE CHAPTER

SAMPLE CHAPTER - PDF document

trinity
trinity . @trinity
Follow
358 views
Uploaded On 2021-06-11

SAMPLE CHAPTER - PPT Presentation

POJOs in Action by Chris Richardson Copyright 2006 Chris Richardson Chapter 1 vii Developing with POJOs faster and easier3J2EE design decisions31 2A 59Using the Domain Model pa ID: 839582

object application spring business application object business spring server design code bean container easier tier transfer objects logic pojos

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "SAMPLE CHAPTER" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1 SAMPLE CHAPTER POJOs in Action by Chr
SAMPLE CHAPTER POJOs in Action by Chris Richardson Copyright 2006 Chris Richardson Chapter 1 vii Developing with POJOs: faster and easier3J2EE design decisions31 2A ................... 59Using the Domain Model pattern61Overview of persisting a domain model95Persisting a domain model with JDO 2.0149Persisting a domain model with Hibernate 3195Encapsulating the business logic with a POJO façade243........................................... 287Using an exposed domain model289Using the Transaction Script pattern317Implementing POJOs with EJB 3360 viiiBRIEF CONTENTS 4D .......................................405Implementing dynamic paged queries407Database transactions and concurrency451Using offline locking patterns488 3 faster and easier This chapter coversComparing lightweight frameworks and EJBsSimplifying development with POJOsDeveloping an object-oriented designMaking POJOs transactional and persistent 4CHAPTER 1Developing with POJOs: faster and easier value. A few years ago I had to go out of the country on a business trip, and Ididn’t

2 want to risk missing episodes of my fav
want to risk missing episodes of my favorite show. So, rather than continu-, I bought a TiVo box. At thetime I thought it was simply going to be a much more convenient and reliable wayto record programs. The TiVo box certainly made it easy to record a show, but I had a similar experience with plain old Java objects (Spring. I was part of a team developing a server product that had a “classic” Enter-) architecture: the business logic consisted of session beans definitely helped by handling infrastructure issues such astransaction management, security, and persistence—but at a high price. Forthe components in the application server. We also jumped through all kinds of The final straw was when we were faced with having to support the product ontwo application servers. Rather than endure the lack of portability of container-the same way on both application servers and eliminated the need to maintain two deployment descriptors. But before long wediscovered other, much more important benefits of Hibernate. It enabled us to domain model in the ne

3 xt version of the prod-application serve
xt version of the prod-application server or a database. And soon after we discovered the Spring frame- services. In hindsight, it’s amazing that we accomplished as much describes how Spring, Hibernate, and Java Data Objects (develop testable and maintainable applications. You will learn how object-BATIS The disillusionment with EJBs5 better characteristics: good object-oriented design, testability, less complexity, eas-ier maintenance, and a raft of other benefits. However, it’s important to remem- 1.1The disillusionment with EJBsThis book isn’t a screed about why you shouldn’t use “traditional” Java 2 Enter-) architecture and design. It is sometimes the best tool for thejob, and later on in this book I describe when you should use it. However, todaymany developers use it for applications for which it is ill suited. Let’s briefly reviewthe history of s and discover why the Java development community’s initialenthusiasm for them has turned into disillusionment. After that, I will describe an1.1.1A brief history of EJBs is the Java standard a

4 rchitecture for writing distributed busi
rchitecture for writing distributed business applications.It’s a framework that provides a large number of useful services and handles someof the most time-consuming aspects of writing distributed applications. For exam- container automatically starts, commits, andactions was a huge innovation at the time and is still a vital service. In addition,s also provide declarative security, whichrequirement handled by the application server. Entries in the bean’s deployment version 1.0 was released in 1998. It provided two types of enterprise beans:session beans and entity beans. Session beans represent either stateless services or fulfilled itsbuilding distributed enterprise systems. refined the programmingmodel. It added message-driven beans (which process Java Message Service, or 6CHAPTER 1Developing with POJOs: faster and easier by the container. The evolution continues in (described later in thischapter), which simplifies the programming model considerably by enabling1.1.2A typical EJB 2 application architectureLet’s look at an example of a

5 typical you work for a bank and you have
typical you work for a bank and you have to write a service to transfer money between two to implement the money trans-fer service. The business logic consists of the and data access objects is a session bean that defines the interface thatthe business logic exposes to the presentation tier. It also implements the busi- The calls the to retrieve the two accounts, andperforms any necessary checks and other business logic. For example, it verifies contains sufficient funds and will not become overdrawn. The calls again to save the updated accounts in the TransferResult transfer(fromAccountId, toAccountId, amount) session beanE.9;E.9;TransferService AccountDTO loadAccount(accountId)saveAccount(AccountDTO) AccountDAO to -55;&#x.800; -55;&#x.800;TransferResult createTransaction()findRecentTxns() TransactionDAO accountIdbalance AccountDTO txnIddate to -55;&#x.800; -55;&#x.800;TransactionDetails Figure 1.1The money transfer service implemented using a typical EJB-based design The disillusionment with EJBs7 returns a DTO th

6 at contains the the customer. The archit
at contains the the customer. The architecture. However, for reasons I describe later, entity beans have severaldrawbacks and limitations. As a result, many applications use The class design and their relationships are simple. I haven’t shown the is ready to be invoked remotely and to participate in distributed transac-1.1.3The problems with EJBsyears writing applications whose design was similar to the one you just saw. I was soexcited about using the new standard that I thought nothing of abandoning theobject-oriented design skills I’d spent the previous decade learning. I was more configuration files just to do the sim-plest things. I found ways to pass the time while my code deployed. After all, isn’t It is certainly true that some aspects of developing enterprise applications arehave high throughput and availability. However, while solves some problemsmaking it easy to write applications. Ironically, in order to be a competent devel- is by Bruce Tate [Tate 2003]. applications, such asCore J2EE Patterns ns EJB Design Patterns [Mari

7 nescu 2002], which con- and solutions to
nescu 2002], which con- and solutions to problems rather than pat- Although these books help developers grapple with and learn how to use iteffectively, they don’t directly address the two fundamental problems with 8CHAPTER 1Developing with POJOs: faster and easier s doesn’t allow developers to take advantage of many of the bestThe shortcomings of procedural designoriented. The procedural approach organizes the code around functions thattures are populated, passed as parameters to functions, and returned to the caller.The relationship between the data and the operations is very loosely defined, andwholly maintained by the developer. Prior to object-oriented languages, this style By contrast, the object-oriented approach organizes code around objects thathave state and behavior and that collaborate with other objects. The data struc-tures and operations are defined in one language construct, co-locating the dataand the operations on the data. The relationship (and state) between the data Despite the benefits of an object-oriented design, mo

8 st applications,including the one shown
st applications,including the one shown in figure 1.1, are written in a procedural style. In our method and possibly one or more helper meth- implement anybusiness logic. These objects exist to provide plumbing and services to theJDBCfits the definition of procedural code exactly. The procedural design style isn’t a problem if the business logic is simple, butbusiness logic has a habit of growing in complexity. As the requirements changeand the business logic has to implement new features, the amount of code in the EJB to implementthat new policy. Even if each enhancement only adds a few lines of code, ones that I encountered on one early project that were each many hundred The disillusionment with EJBs9 EJBs like these that contain large amount of code cause several problems. Thelack of modularity makes them difficult to understand and maintain because it’sextended to support new requirements only by adding more code, which makess are also very difficult to test because they lackWhy J2EE encourages developers to write procedural codeTher

9 e are a couple of reasons why developer
e are a couple of reasons why developers often write procedural-style specifi-cation makes it seductively easy. Although the specification does not force you toless, procedural code. When implementing new behavior, you don’t have to worryabout identifying classes and assigning responsibilities as you would if you weredesigning a real object model. Instead, you can write a new session bean method The second reason why developers write procedural-style code is that it is architecture, literature, and culture, which place great components. components are not suitable for implementinguse them in an application is to encapsulate an object model: the and entity beans, which are intended to represent business objects, have numer-tent object model. This is why I didn’t use them in our earlier example. entityand occur when object A calls object B, which calls object A. We’ll discuss other lim-itations of entity beans in a moment. Entity beans have so many limitations that it’samazing that developers have used them successfully. This is a fundame

10 ntal prob- architecture. Each framework
ntal prob- architecture. Each framework creates a path of least 10CHAPTER 1Developing with POJOs: faster and easier As a result, it has been difficult to do any true object-oriented development in application. Furthermore, this procedural design style is so ingrained in culture that it has even carried over into newer, non- ways of develop- applications. Some developers still view persistent objects simply as a applications. Some developers still view persistent objects simply as aas anemic blood lacks vitality, anemic object models only superficially model theThe pain of EJB developmentYou must deal with annoyingly long edit-compile-debug cyclesserver-side components, you must deploy them in the container, whichwhich point you might be tempted to do something else, like surf the Web a friend. The impact on productivity is particularly frustrating whendoing test-driven development, where it is desirable to run the tests fre-quently, every minute or two. Test-driven development and unit testing areYou face a lack of separation of concerns o

11 ften forces you to solve several dif-pro
ften forces you to solve several dif-problem at a time. Not only is this mentally overwhelming but it also adds toYou must write a lot of code to implement an EJB—You must write a home inter-face, a component interface, the bean class, and a deployment descriptor,which for an entity bean can be quite complex. In addition, you must writebut that are required by the interface the bean class implements. This codeisn’t conceptually difficult, but it is busywork that you must endure. You have to write data transfer objectspresentation tier will display to the user. It is often just a copy of the data The disillusionment with EJBs11 from one or more entity beans, which cannot be passed to the presentations can be a slow, mind-numbing process. While you can get used toit and find ways to occupy your time while waiting for components to deploy, it isn’ta good way to develop software. As I mentioned earlier, the nature of develop- precludes many of the best practices common in other types of Javadevelopment. Because the components must run in the ap

12 plication server in orderto access the s
plication server in orderto access the services it provides, an incremental development strategy that fre-quently executes the edit-compile-debug cycle is difficult. Eventually, many enter-started to ask questions: Does the development I’m doing require all these services1.1.4EJB 3 is a step in the right direction standard isn’t frozen in amber. The designers of the specifications at Sunlisten to developers and are modifying the specification accordingly. The standard is to simplify development. It addressesless coupled to the application server environment. entity beans are intended to be the standard Java persistence mecha- supports the use of Java 5 annotations instead of difficult-to-write entity beans can be used to return data to the presentation tier, which still has limitations. For example, it forces components into three categories—session beans, entity beans, and message-driven beans—even though in a typical 12CHAPTER 1Developing with POJOs: faster and easier a result, many classes are unable to use the services provided by the

13 container. containers still appears toI
container. containers still appears toI describe later in this chapter. Despite its limitations, it is extremely likely that will be widely used for the standard. It is also important to remember is an appropriate implementation technology for two types of applications: 1.2Developing with POJOs specification was written, some developers disillusioned started to look for alternative frameworks. POJOs are an especially com-any special interfaces such as those defined by the framework. The name wascoined by Fowler, Rebbecca Parsons, and Josh MacKenzie [Fowler However, need services such as transaction management, security, and persistence, which container. The solution is to use the increas- stack. They do not completely replace the stack but can beused in combination with some parts of it to provide important enterprise services. The four lightweight frameworks that I describe in this book are Hibernate, BATISby the community. Hibernate and are persistence frameworks, which map and significantly Developing with POJOs13 increase developer

14 productivity. iBATIS is also layered on
productivity. iBATIS is also layered on top of statements and is a very convenient way to execute statements., including the equivalent of container-managed transactions for An important feature of these technologies is that they are nonintrusive.application classes to implement any special interfaces. Even when your applica-tion’s classes are transactional or persistent, they are still s that I describe in this chapter. Some excellent books are available that describe these frameworks in depth:Hibernate in Action [Bauer 2005], [Walls 2005], BATIS in Action in ActionJava Data Objects [Russell 2003]. You do not need to In this section I will provide an overview of how to use frameworks to redesign the money transfer service and make it easier to develop, instead of using directly. The business logic is façade instead of a session bean, and transactions are container. The businessDTOapplication is assembled by passing a component’s dependencies as setter or con-structor arguments instead of the component using Java Naming and DirectoryIn

15 terface ( lookups. Because the design is
terface ( lookups. Because the design is object-oriented and uses theselightweight technologies, it is much more developer-friendly than the versionwe saw earlier. Table 1.1 summarizes the differences between the two designs.Table1.1Comparing classic EJB and POJO approaches Classic EJB approach OrganizationProcedural-style business logicObject-oriented designImplementationEJB-basedPOJOsDatabase accessJDBC/SQL or Entity beansPersistence framework Returning data to the DTOsBusiness objects 14CHAPTER 1Developing with POJOs: faster and easier Don’t worry if you are not familiar with all of these terms. In this section, I’ll approach. You will seehow to develop business logic using the approach. I use the money transfer1.2.1Using an object-oriented design and its helper methods, the code should be structured around an that coordinates the transfer of money fromone account to another. Figure 1.2 shows the design.Transaction managementEJB container-managed Spring frameworkApplication assemblyExplicit JNDI lookupsDependency injectionTable1.1Compa

16 ring classic EJB and POJO approaches (c
ring classic EJB and POJO approaches (continued) POJO approach debit(amount)credit(amount) balance date BankingTransaction allow(Account, amount) interface&#x-10.;က&#x-10.;ကOverdraftPolicy NoOverdraftPolicy LimitedOverdraft TransferTransaction from BankingTransaction transfer(fromId, toId, amount) TransferService Figure 1.2An object model for the money transfer application Developing with POJOs15 maintains its balance and has an is isof OverdraftPolicy: one for each type of real-world policy. Better yet, an could encapsulate a rules engine and thereby enable the business rules foroverdrafts to be changed dynamically. Using an object-oriented design has a number of benefits. First, the design iseasier to understand and maintain. Instead of consisting of one big class that doeseverything, it consists of a number of small classes that each have a small number closely mirror the real world, which makes their role in the Second, our object-oriented design is easier to test: each class can and shouldbe tested independently. For example, w

17 e could write unit tests for andtested
e could write unit tests for andtested by calling its public methods, for example, difficult. You can only test the complex functionality exposed by the public meth- Finally, the object-oriented design in figure 1.2 is easier to extend because itTemplate pattern [Gang of Four]. Adding a new type of overdraft policy simply-style procedural design usually requires changing the core code, and rewrit-ing or chaining procedure calls together. As you can see, our object-oriented design has some important benefits. But it1.2.2Using POJOs programming model,implementing the object model shown in figure 1.2 is easy. Java provides all of thenecessary features, including fine-grained objects, relationships, inheritance, andrecursion. It is straightforward to implement expressive object models like thiss and thus benefit from improved maintainability and testability. 16CHAPTER 1Developing with POJOs: faster and easier —There is less cognitive load because rather than beingforced to think about everything—business logic, persistence, transactionsetc.—at

18 once you can instead focus on one thing
once you can instead focus on one thing at a time. You can firstdesign and implement the business logic and then, once that is working,—You can develop and test your business logic outside ofthe application server and without a database. You do not have to packagewaiting for slow-running database tests to finish. Tests can run in a few sec-Improved portability—You are not tied to a particular implementation tech-nology. The cost of switching to the next generation of Java technology isminimized because you have to rewrite only a small amount of code, if any. approach. As with theTiVo box I described earlier, I had to use them before I appreciated their truevalue. But now I couldn’t imagine reverting to the old way of working. Of course,you still need to handle persistence and transactions, which is where lightweight1.2.3Persisting POJOsthere are some powerful object/relational mapping frameworks to choose from.JDOentity beans appears to be potentially quite powerful.Transparent persistence with JDO and HibernateJDO and Hibernate provide tran

19 sparent persistence, which means that th
sparent persistence, which means that the classesare unaware that they are persistent. The application just needs to call the persis-s to save, query, and delete persistent objects. The persis- statements that access the docu- Developing with POJOs17 and Hibernate can also run outside of the application server,which means that you can test your persistent business logic without deploying itin a server. You can, for example, simply run tests from within your integratedEncapsulating the calls to the persistence frameworkJDO provide transparent persistence, some parts of and Hibernate s to save, query, and delete must call the persistence frame- to call the persistence framework s directly. Unfortu-nately, this would couple directly to the persistence framework A better approach is to encapsulate the Hibernate or code behind an inter- debit(amount)credit(amount) BankingTransaction BankingTransaction transfer(fromId, toId, amount) TransferService findAccount(id) nterfac&#xi-62;&#x.600;&#xi-62;&#x.600;eRepository Hibernate createTransaction( n

20 terfac&#xi-62;&#x.500;&#xi-62;&#x.500;eB
terfac&#xi-62;&#x.500;&#xi-62;&#x.500;eBankingTransactionRepository findAccount(id)HibernateRepository createTransaction( HibernateBankingTransactionRepository Figure 1.3Using repositories to encapsulate the persistence framework 18CHAPTER 1Developing with POJOs: faster and easier Hibernate, is encapsulated by the repository classes. Each repository consists of aninterface and a Hibernate implementation class and is responsible for one type of implementation would be similar. In this example, repositories call the Hibernate finds accounts and creates is written in terms of the and interfaces, which decouples itfrom the persistence framework and the database. By the intelligent use of inter- or even is simply a matter of changing the concrete classesthat access the persistence framework. It’s a generally accepted observation that1.2.4Eliminating DTOs application is to eliminate the is a simple object consisting of only fields (i.e., no behavior)and is used to return data from the business tier to the presentation tier. An the presentat

21 ion tier. Each call to an entity bean mi
ion tier. Each call to an entity bean might be a remote call and/or as, however, is that they and the code that creates them are extremely tedious application. objects do not have this limitation and can be accesseddirectly by the presentation tier. As a result, we eliminate many or all of the JDOsentation tier. One option is for the business tier to return objects that are still Developing with POJOs19 Another approach, which is described in detail in chapter 7, is for the businessthe persistent tier. This approach eliminates the need for database accesses in the business tier. Different persistence frameworks handle detached objects in different ways. Inensure that all of the objects required by the presentation tier are loaded, which anUsing a façade to retrieve calling the persistence framework to retrieve and detach the objects required bythe presentation tier. For example, the money transfer business logic mustYou could make this the responsibility of the , but doing so wouldmake it more complicated and couple it to the needs of the p

22 resentation tier.Moreover, because the b
resentation tier.Moreover, because the business tier must sometimes call the persistent frameworkto ensure that the domain objects can be returned to the presentation tier, mak- call the detachment logic would mix together pure busi- Unless the service is very simple and contains little or no business logic, a bet- implements the interface, which specifies the methods that can be called by thebusiness logic’s client and plays a role similar to that of an component inter- Like the we saw earlier, defines a method that and is the only in1.2.5Making POJOs transactionalLet’s review what we have done so far. We replaced a procedural design with an 20CHAPTER 1Developing with POJOs: faster and easier the edit-compile-debug cycle is extremely short. We now have an applicationwhere most of the code is sufficiently modular that you can write unit tests. Wehaven’t yet discussed how to eliminate the Let’s see what we can do about that.are used in many applications is because they provide container-managed trans- container automatically starts a tr

23 ansaction when a businessmethod is invok
ansaction when a businessmethod is invoked and commits the transaction when the method returns. It is thrown. Container-managedtransactions are extremely useful. They free you from writing error-prone code tomanually manage transactions. Consequently, if you want to replace session BankingTransaction transfer(fromId, toId, amount) TransferService BankingTransaction transfer(fromId, toId, amount) TransferFacadeImpl findRecentTxns() nterfac&#xi-62;&#x.600;&#xi-62;&#x.600;eTransactionRepository TransferResult transfer(fromId, toId, amount) interface&#x-10.; &#x-10.; TransferFacade TransferResult BankingTransaction Figure 1.4The design of , which encapsulates the business logic and Developing with POJOs21 very popular framework that provides this capability is Spring. Spring is a power- application framework that makes it significantly easier to develop enter-to provide a brief overview of a few of them in this chapter. For more information[Walls 2005]. The Spring framework provides an extremely easy-to-use mechanism for mak-s transactional

24 that works in a similar way to containe
that works in a similar way to container-managed transac-tions. Spring will automatically begin a transaction when a method isinvoked and commit the transaction when the method returns. It can also rollapplication server’s implementation of the Java Transaction JTA. Alternatively,s, which are simpler and easier to use because they do notrequire an application server. When using the Spring framework, we can make a transactional by defin- issimilar to a deployment descriptor and configures Spring’s lightweight container,which is a sophisticated factory for constructing objects. Each entry in the application obtains a bean by calling the Spring bean factory with the name andThis code fragment calls the method with as the name of the bean and as the expected class. Thebean factory will throw an exception if a bean with that name does not exist or is As well as being a highly configurable way to instantiate objects, a Spring beanfactory can be configured to return a proxy instead of the original object. Aproxy, which is also known as an int

25 erceptor, is an object that masquerades
erceptor, is an object that masquerades as theoriginal object. It executes arbitrary code before and after invoking the original 22CHAPTER 1Developing with POJOs: faster and easier including security, database connection man- In this example application, we can config-ure the Spring bean factory to wrap with a proxy that manages transactions.To do that, we must define several beans, bean, along and The bean wraps with a in this exam-ple is implemented by the class, which uses the interface to begin, commit, and roll back transactions. List- configuration file that defines these beans. Listing1.1Configuring Sprin TransferFacadePlatformTransactionManager TransactionInterceptor BeanNameAutoProxyCreator TransferFaçade TransactionInterceptor PlatformTransactionManager Figure 1.5The Spring bean definitions Developing with POJOs23 class="org.springframework.aop.framework.bbbbbbbbb&#xprop;rty;&#x nam;="b;ênN; mes;&#x"000; &#x/pro;&#xpert;&#xy000; &#xprop;rty;&#x nam;="i;&#xnter;Îpt;&#xorNa;&#xmes"; &#xlis

26 t; &#xidre; be; n=";&#xTra
t; &#xidre; be; n=";&#xTran;&#xsact;&#xionI;&#xnter;Îpt;&#xor"/; &#x/lis;&#xt000; &#x/bea;&#xn000; Let’s take a closer look at this listing: class that manages transactions using the class that makes an object transactional. intercepts calls to the object and calls a to begin, commit, and roll back transactions. It has a property, to use, and a property, which specifies which methods to make transactional. In with property, whichspecifies the list of interceptors to apply, and a property, which specifiesThese bean definitions arrange for the bean factory to wrap with is invoked instead. The sequence ofTransactionInterceptor to the TransferFacade BCDE 24CHAPTER 1Developing with POJOs: faster and easier Let’s look at the sequence of events:The presentation tier calls but the call is routed to begins a transaction by calling , which begins a transaction using either the JTA provided bythe application server or the transaction management provided by the commits the transaction by calling could also r

27 oll back the transaction if the service
oll back the transaction if the service threw an exception. By default, is thrown.However, you can write rollback rules that specify which exceptions should causedecouples it from the transaction management programmatically rolls back transactions. This is one example of how the Spring container. Another benefit of using Spring is that you can test your transactional without deploying them in the application server. Because code that uses or PresentationTier TransactionInterceptor TransferFacadeImpl 1. Call transfer() 3. Call transfer() 4. transfer() returns PlatformTransaction Manager 2. Begin transaction 5. Commit transaction 6. transfer() returnsFigure 1.6Using Spring inte Developing with POJOs25 without ever starting up an application server. In fact, I often find that the only timeI need to use one is when developing code that uses a service such as that is pro-vided by the application server. Even when working on the presentation tier I’mable to use a simpler web container such as Jetty. This is yet another example of howlightweight

28 frameworks make your life as a develope
frameworks make your life as a developer easier.The role of AOP in the Spring frameworkThe technology underlying Spring’s transaction management mechanism is is a declarative mechanismthe application itself. You write rules that specify new code to be executed whenmethods are called and, in some cases, fields are accessed or objects instantiated.In this example the arranged for the to be executed whenever the was called without any is not limited to transaction management, and in this bookyou will see examples of interceptors that implement security, manage databaseconnections, and automatically retry transactions. I’m using the Spring implementation in this book for the simple reason interceptors for managing transactions, interceptors for managing transactions, AOP mechanisms like AspectJ [Laddad 2003].However, as of this writing, Spring provides the best implementation of the features The Spring framework is one example of a growing number of technologies provides the same ben- session beans but also allows you to use container pro

29 vides a large number of services, includ
vides a large number of services, including transac-tion management. But is it worth compromising the design of the application totake advantage of these services—especially if you can implement them using a1.2.6Configuring applications with SpringMost applications consist of multiple components that need to access one another. application uses as the mechanism that one componentuses to access another. For example, the presentation tier uses a lookup toobtain a reference to a session bean home interface. Similarly, an to 26CHAPTER 1Developing with POJOs: faster and easier is that it couples application code to the application server, which makeswith a much easier-to-use mechanism called application components from one another and from the application server. Dependency injection is another powerful feature of Spring’s bean factory.essary. Two main types of dependency injection are used with Spring: constructorrequired objects to a component’s constructor; with setter injection, the con- Dependency injection was used earlier to wire toget

30 her the Spring beans— bean to depend on
her the Spring beans— bean to depend on and to depend on and ’s constructor take a as a parameter. The second bean definition specifies that ’s constructor be passed and Developing with POJOs27 http://www.manning.com/crichardson, for the definition of the Dependency injection is an extremely easy way to configure an application.automatically passed in by the bean factory. It doesn’t have to call any applicationserver s. In chapter 7, I’ll show how dependency injection is a useful way of decou-pling components from one another and the application server environment. 1.2.7Deploying a POJO applicationAs I mentioned earlier, one of the great things about tion server. Eventually, however, you do need to deploy the application. An appli- forpersistence can often be deployed in a simple web container-only server such asJetty, Tomcat, or WebLogic Express, as shown in figure 1.7. The application is simply packaged as a web archive file (WARthe server’s web container. It would use either a connection pool provided by Application Server Web Con

31 tainer Business Tier Presentation Tier S
tainer Business Tier Presentation Tier Servlets Browser JDBC Connection Spring Hibernate/JDO Figure 1.7Deploying a POJO application in a web container 28CHAPTER 1Developing with POJOs: faster and easier the application server or an open source implementation such as ver or an open source implementation such as DBCP]. Ifthe application needed to be clustered for scalability and reliability, then it woulduse the clustering feature of the web container. An application only needs to be deployed in a full-blown application server(e.g., WebLogic Server or JBoss) if it requires those parts of the stack such asJTA or that are not provided by the web container or some third-party soft-ware. You might also want to deploy your application in a particular server if youwanted to use a vendor-specific feature. For example, some application serversand, in some cases, cheaper server.1.2.8POJO design summaryLet’s review the design of the money transfer service that uses a object model,-based design described earlier in section 1.1.2. However, this more

32 modulardesign is easier to understand, t
modulardesign is easier to understand, test, and extend than the original version. Each classof interfaces for the repositories simplifies testing by allowing the real implemen- enables the The core of the business logic consists of object model described earlier in sec- and and classes encapsulate the provides a method for creating transactions. is a simple service that looks up the accounts by calling and calls and on them. It also creates a to record the transfer.data required by the presentation tier. This functionality could be implemented focused on transferring money and away from the presentation tier and is wrapped with a Spring Developing with POJOs29 container. By using also have a design and structure of code that is impossible if we use the heavyweight application server and all its services. Using the lighter weight tools allows usto improve the structure, maintainability, and testability of our code. Spring TransactionInterceptor debit(amount)credit(amount) BankingTransaction BankingTransaction transfer(fromId, toId,

33 amount) TransferService findAccount(id)
amount) TransferService findAccount(id) interface&#x-10.; &#x-10.; Repository nterfac&#xi-62;&#x.600;&#xi-62;&#x.600;eOverdraftPolicy TransferResult transfer(fromId, toId, amount) TransferFacadeImpl Hibernate createTransaction(...) interface&#x-10.; &#x-10.; BankingTransactionRepository NoOverdraftPolicy LimitedOverdraft findAccount(id) HibernateRepository createTransaction(...) HibernateBankingTransactionRepository TransferResult transfer(fromId, toId, amount) interface&#x-10.; &#x-10.; TransferFacade TransferResult Figure 1.8Money transfer service implem 30CHAPTER 1Developing with POJOs: faster and easier 1.3SummaryJDO hassome surprising benefits. You have the freedom to develop expressive object mod-els rather than being forced down a procedural path. You get the benefits of such as declarative transaction management and security, but in a much moredeveloper-friendly form. You can work on your core business logic without beingYou can develop and test your code wi In the next chapter we look at the design decisions you need to make whe