ebook img

Google Guice: Agile Lightweight Dependency Injection Framework PDF

189 Pages·2008·1.83 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Google Guice: Agile Lightweight Dependency Injection Framework

EMPOWERING PRODUCTIVITY FOR THE JAVA™ DEVELOPER Available as a PDF Electronic Book G or Print On Demand Apress’s firstPress series is your source for understanding cutting-edge technology. Short, highly o focused, and written by experts, Apress’s firstPress books save you time and effort. They contain o the information you could get based on intensive research yourself or if you were to attend a g conference every other week—if only you had the time. They cover the concepts and techniques le that will keep you ahead of the technology curve. Apress’s firstPress books are real books, in your G choice of electronic or print-on-demand format, with no rough edges even when the technology u Google itself is still rough. You can’t afford to be without them. i c e Google Guice: Agile Lightweight Guice Dependency Injection Framework Dear Reader, This book welcomes you to the world of Google Guice (pronounced “juice”), the latest and greatest dependency injection framework that fully exploits all modern Java™ features. One step at a time, this book will help turn any XML-spitting programmer into a true Guice master, or a “Bob,” as I like to say. I’m particularly proud of this book’s coverage. To make sure that nobody gets left behind, I start out with an introduction to dependency injection concepts. From there, you will learn how Guice makes your life easier, and you’ll gradually become a Guice expert. Beyond that, I also devoted two chapters to web application development with Struts 2 and Wicket, including content on how to organize your application and Agile Lightweight Dependency how to use Warp Persist, a popular Guice extension, to access your data using the Java Persistence API and Hibernate. Writing this book was not an easy task, so in addition to Apress, I’d like to thank Injection Framework some people in particular. First, I would like to thank Dhanji R. Prasanna for referring me to Apress to write this book. He has also done a fantastic job as my technical reviewer. I’d also like to thank Bob Lee, the inventor of Guice, who kindly answered all of my questions and inspired much of the content in Chapter 8. Finally, a big thank you goes out to my friends, my parents, my brother, and anyone who believes in me; you are the people who put the smile on my face. Now, put on your Batman or Catwoman costume; open up a bottle of wine; pick up this book; and put your feet up. Be a Java hero, and may Guice help you on your way. Just don’t forget to send me a picture of you in that getup. 180 Robbie Vanbrabant PAgeS http://garbagecollected.org V a Robbie Vanbrabant n b r a SOURCE CODE ONLINE b www.apress.com a n java.apress.com t User level: Intermediate this print for content only—size & color not accurate spine = 0.408" 192 page count About firstPress Apress's firstPress series is your source for understanding cutting-edge technology. Short, highly focused, and written by experts, Apress's firstPress books save you time and effort. They contain the information you could get based on intensive research yourself or if you were to attend a conference every other week—if only you had the time. They cover the concepts and techniques that will keep you ahead of the technology curve. Apress's firstPress books are real books, in your choice of electronic or print-on-demand format, with no rough edges even when the technology itself is still rough. You can't afford to be without them. Google Guice: Agile Lightweight Dependency Injection Framework Dear Reader, This book welcomes you to the world of Google Guice (pronounced “juice”), the latest and greatest dependency injection framework that fully exploits all modern Java™ features. One step at a time, this book will help turn any XML-spitting programmer into a true Guice master, or a “Bob,” as I like to say. I’m particularly proud of this book’s coverage. To make sure that nobody gets left behind, I start out with an introduction to dependency injection concepts. From there, you will learn how Guice makes your life easier, and you’ll gradually become a Guice expert. Beyond that, I also devoted two chapters to web application development with Struts 2 and Wicket, including content on how to organize your application and how to use Warp Persist, a popular Guice extension, to access your data using the Java Persistence API and Hibernate. Writing this book was not an easy task, so in addition to Apress, I’d like to thank some people in particular. First, I would like to thank Dhanji R. Prasanna for referring me to Apress to write this book. He has also done a fantastic job as my technical reviewer. I’d also like to thank Bob Lee, the inventor of Guice, who kindly answered all of my questions and inspired much of the content in Chapter 8. Finally, a big thank you goes out to my friends, my parents, my brother, and anyone who believes in me; you are the people who put the smile on my face. Now, put on your Batman or Catwoman costume; open up a bottle of wine; pick up this book; and put your feet up. Be a Java hero, and may Guice help you on your way. Just don’t forget to send me a picture of you in that getup. Robbie Vanbrabant http://garbagecollected.org Contents Chapter 1: Setting the Stage.........................................................................................1 The Problem...................................................................................................................................1 A Fortunate Example....................................................................................................................3 Dependency Injection....................................................................................................................5 DI, Guice Style..............................................................................................................................8 Summary......................................................................................................................................10 Chapter 2: Enter Guice..............................................................................................11 Getting Guice...............................................................................................................................11 Preparing the Code......................................................................................................................12 Specifying an Implementation....................................................................................................15 Bootstrapping...............................................................................................................................15 Choosing Between Implementations..........................................................................................17 Implicit Bindings.........................................................................................................................21 Scoping.........................................................................................................................................22 Debunking Myths........................................................................................................................23 Summary......................................................................................................................................27 Chapter 3: From Journeyman to Bob.........................................................................29 Providers......................................................................................................................................29 @Named......................................................................................................................................32 Binding Constants.......................................................................................................................34 Binding Generic Types...............................................................................................................38 Properties.....................................................................................................................................42 Static Injection.............................................................................................................................44 Google Guice: Agile Lightweight Dependency Injection Framework i Custom Scopes............................................................................................................................45 Web Scopes..................................................................................................................................49 Organizing Modules....................................................................................................................51 The Binding EDSL......................................................................................................................53 How Guice Resolves Dependencies...........................................................................................56 Summary......................................................................................................................................57 Chapter 4: Aspect-Oriented Programming.................................................................59 AOP for Mere Mortals................................................................................................................60 How Guice AOP Works..............................................................................................................60 Method Interception....................................................................................................................61 Phoning Home.............................................................................................................................64 Summary......................................................................................................................................69 Chapter 5: Integrating with the Web...........................................................................71 The Integration Challenge...........................................................................................................71 Bootstrapping...............................................................................................................................72 Inviting Servlets to the Club.......................................................................................................73 Configuration Discovery.............................................................................................................74 Struts 2.........................................................................................................................................76 Wicket..........................................................................................................................................78 Where Are the Web Scopes?......................................................................................................85 Warp Servlet................................................................................................................................86 Summary......................................................................................................................................92 Chapter 6: Practical Guice.........................................................................................93 Requirements...............................................................................................................................93 The Big Picture............................................................................................................................95 Project Structure..........................................................................................................................99 Setting Up Struts 2....................................................................................................................103 Getting Guiced...........................................................................................................................104 76a2626bcfb21763948a3d635f6fe985 ii Google Guice: Agile Lightweight Dependency Injection Framework Defining the Model...................................................................................................................105 Database Access with Warp Persist.........................................................................................109 Implementing the Data Access Layer......................................................................................111 The Home Screen......................................................................................................................118 The Create and Edit Screens.....................................................................................................121 Unit Testing...............................................................................................................................123 Summary....................................................................................................................................125 Chapter 7: Guice Recipes.........................................................................................127 Sharing Singletons.....................................................................................................................127 Binding Collections...................................................................................................................129 Designing Libraries and Limiting Visibility............................................................................136 Viral Annotations......................................................................................................................138 Mixing Scopes...........................................................................................................................139 Integrating Spring......................................................................................................................142 Logging......................................................................................................................................145 Integrating JNDI........................................................................................................................146 Using JMX.................................................................................................................................147 Summary....................................................................................................................................150 Chapter 8: The Future..............................................................................................153 The Grand Plan..........................................................................................................................153 Growing an Extensible Platform..............................................................................................154 Better Up-Front Checking.........................................................................................................155 Keeping Guice Simple and Making It Simpler.......................................................................156 Improved Tooling Support........................................................................................................158 Addressing DI Shortcomings....................................................................................................160 Standardization..........................................................................................................................164 Summary....................................................................................................................................166 Google Guice: Agile Lightweight Dependency Injection Framework iii Appendix: Assorted Sweets.......................................................................................167 Binder Syntax Explained..........................................................................................................167 Hello Servlet Guice...................................................................................................................169 Hello Wicket Guice...................................................................................................................172 Hello Warp Servlet....................................................................................................................174 SessionPerRequestInterceptor..................................................................................................177 iv Google Guice: Agile Lightweight Dependency Injection Framework Google Guice: Agile Lightweight Dependency Injection Framework by Robbie Vanbrabant Foreword by Bob Lee, Guice Lead I created Guice in the midst of one of the biggest projects of my career. When you have hundreds of engineers touching millions of lines of code, you come to appreciate the benefits of static type checking. Static types aren’t just about compiler errors. In fact, I rarely see Java compiler errors nowadays. Thanks to all that great, formalized Java type information, my IDE helps me write correct code in the first place. Writing your application in a nearly 100 percent type safe manner, like Guice enables and Robbie advocates in this book, opens the door to a new level of maintainability. You can effortlessly navigate unfamiliar code, jumping from interfaces to their implementation and from methods to their callers. As you master your Java tools, you realize that deceptively simple atomic refactorings combine to form molecular tools, which you can reliably apply to companywide swaths of code, accomplishing refactorings you’d never even consider trying by hand. In the long run, it’s much cheaper to ward off bit rot through heavy reuse and constant refactoring than by nuking the world with a rewrite every couple years. Having experienced Guice’s benefits on a number of projects, we at Google knew we couldn’t keep it to ourselves and decided to make it open source. Readying Guice for the outside world felt like it took an order of magnitude more work than writing that first internal version, but community contributors like Robbie who fuel the forums, help polish rough edges, and generate excellent documentation like this book pay back that effort tenfold. You’ll find that Robbie’s brevity and conversational tone suit Guice well. I like my books like I like my APIs: with high power-to-weight ratios. Google Guice: Agile Lightweight Dependency Injection Framework v vi Google Guice: Agile Lightweight Dependency Injection Framework Chapter 1: Setting the Stage You’ve probably heard about dependency injection (DI), and if so, you’re in for a real treat: Guice (pronounced “juice”) is, in my opinion, by far the most innovative framework in the problem space. Created by Google employees “Crazy” Bob Lee (http://crazybob.org) and Kevin Bourrillion (http://smallwig.blogspot.com), this lightweight, open source DI framework is designed to bring true ease of development to the world of DI. Taking advantage of Java 5 features like no other application has before, Guice is the XML-free cure to hard-to-maintain code. Before I start talking about using frameworks, DI, and whatnot, I think it’s best to step back and take a look why initiatives like Guice exist in the first place. Obviously, Guice is not the only DI framework out there. As with model-view- controller (MVC) web frameworks, there are lots of frameworks to choose from in the DI world, and everyone probably has their personal favorite. Whether or not you use Guice after reading this book will depend on your needs, but once you have a good grasp of the concepts described here, your code will never look the same again—whether you use Spring, PicoContainer, Guice, or no framework at all. If this is the first time you’ve heard about DI, don’t worry; this first chapter will explain, from the ground up, the problem at hand, and how Guice helps unravel the mystery of maintainable code. And who knows? This chapter might be a good refresher for experienced DI users. The Problem If you’re in the business of creating software, you ultimately want to have maintainable software. You’ll certainly agree with me that you spend more time maintaining software than writing software—and that the maintainability you need doesn’t come for free. It requires careful design and a well defined process for testing and validating the application. Google Guice: Agile Lightweight Dependency Injection Framework 1 In your professional life, or even as a hobbyist, you’ve probably picked up the concept of unit testing. Basically, it’s about testing little units of source code for validity. Being able to tell with one look at a bar (green or red) whether your code has the right side effects is valuable and will save you time. Unit testing is a no-brainer. In this book, unit test examples will use JUnit 4 (http://www.junit.org). I strongly believe that automated testing, like unit testing, is the best way to achieve software maintainability. With the right amount of test coverage, you can rest assured that, when you’re making changes to the code, you won’t break code somewhere else in the code base. You can simply write your tests, make your change, run the collected set of tests, and feel confident. Poorly designed applications are usually hard to test, which means well tested applications probably aren’t too bad. You can write great software without automated testing—you can also win the lottery, but don’t count on it. So there you have it: unit testing helps achieve maintainability. And what else can help you achieve that? Writing less code, of course! The less code you need to accomplish what you’re trying to do, the less code you’ll need to maintain. Obviously, you can’t just randomly delete blocks of code, but in some cases, code doesn’t really mean anything; it’s just boilerplate to get you from point A to point B. Wouldn’t it be nice if you could get rid of all that noise and focus on the stuff that matters? For lack of a better term, I call this the maintainability mission statement. This is not a complete list, but, among other things, maintainable code needs to be (cid:131) Easy to test (modular) (cid:131) Meaningful (as little noise as possible) You probably already see where I’m going, but before we dive into Guice, let me illustrate how to accomplish these goals in a typical situation. When we’re done with that, we’ll throw Guice into the mix and dance on the ceiling. 2 Google Guice: Agile Lightweight Dependency Injection Framework

Description:
Guice (pronounced "Juice") is the 100% Java icing on the cake of Java dependency injection. Unlike other popular DI frameworks such as Spring, Guice fully embraces modern Java language features and combines simplicity with stunning performance and developer-friendliness. Google Guice: Agile Lightwei
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.