[ Guillaume Laforge ]


Home

CV

Projets

Weblog

Guicy: a Groovy Guice?  —  Ecrit par Guillaume

I recently came across Bob Lee's brand new IoC/DI framework: Guice. I'm usually using Spring for that purpose, and also because it goes much farther than just IoC/DI, but I thought I'd give Guice a try, especially because I wanted to play with Groovy's support for annotations. So I downloaded Guice, and read the nice getting started documentation I also took a snapshot of Groovy 1.1 that supports Java 5 annotations. With guice-1.0.jar and aopalliance.jar on my classpath, and with the latest Groovy snapshot distribution properly installed, I was ready to go!

So, how do we start? Well, first of all, you must have some service contract that you'd like to depend on and to inject in some client code. Nothing really fancy here, I just shamelessly took inspiration from the documentation:

interface Service {
    void go()
}
Now, I need a concrete implementation of this service:
class ServiceImpl implements Service {
    void go() {
        println "Okay, I'm going somewhere"
    }
}
So far so good, now, we'll need some client code that needs a service to be injected. This is where you're going to see some specific juicy annotation coming into play.
class ClientWithCtor {

    private final Service service

    @Inject
    Client(Service service) {
        this.service = service
    }

    void go() {
        service.go()
    }
}
Here, I'm creating a client class where I'm using constructor injection. The sole thing we have to do here is just use the @Inject annotation. But of course, so far, the wiring isn't specified anywhere, and we have to do it now. Guice has the concept of Modules which contain programmatic code to wire classes together.
class MyModule implements Module {
    void configure(Binder binder) {
        binder.bind(Service)
            .to(ServiceImpl)
            .in(Scopes.SINGLETON)
    }
}
We are binding the Service interface to the ServiceImpl implementation. And we also mention the scope of the injection: we want to have one single implementation of that service available. Instead of specifying the scope in the module, you could also use a @Singleton annotation on the ServiceImpl class.

Now that everything is in place, we can create a Guice's injector and retrieve and call a properly wired client with the following code:

def injector = Guice.createInjector(new MyModule())

def clientWithCtor = injector.getInstance(ClientWithCtor)
clientWithCtor.go()

Instead of the constructor-based approach, I prefer using a setter-based approch. And since Groovy creates getters and setters automagically when you define a property, the code is a bit shorter:

class ClientWithSetter {

    @Inject Service service

    void go() {
        service.go()
    }
}
And the code for injecting is still the same:
def clientWithSetter = injector.getInstance(ClientWithSetter)
clientWithSetter.go()

I'm not sure I'd use Guice for a customer project anytime soon, but for small projects where I want a xml-free DI framework, that might do! However, I might be tempted to use Grails' Spring bean builder instead, since it's a pretty cool way to avoid the usual XML-hell when working with Spring. Also, in conclusion, it seems that Groovy's new support for annotations work quite well, as demonstrated also by Romain while integrating Groovy and JPA. I'm sure this will propel Groovy as the de facto enterprise scripting solution leveraging the wealth of frameworks and libraries using annotations.



posté le 26.03.2007 à 23:22:14 par Guillaume - Catégorie : Java

Liens

Commentaires

Romain Guy a écrit :

That looks cool. It reminds me of PicoContainer and NanoContainer for that matter. Doesn't NanoContainer offer support for Groovy by the way?
26.03.2007 23:47:30

Guillaume a écrit :

I haven't looked at NanoContainer for a while, but yes, it has a nice support for Groovy!
26.03.2007 23:53:45

Paul Hammant a écrit :

Yup, NanoContainer has Groovy builder support. Working for various degrees of sophistication since 2004.
27.03.2007 07:14:37

Marcus Breese a écrit :

I'm not sure that Groovy's auto generated getter/setter is what is used with the "@Inject Service service"
code. Guice will also inject a field directly w/o a setter, so it would be interesting to see exactly where the injection is in your above example.

I'm not quite sure _how_ to check, but it would be interesting.
28.03.2007 22:44:52

Dick Wall a écrit :

Nice job there - I was thinking today that Groovy would make a great binding configurator for Guice, because it means you can re-configure the dependency configuration without needing a Java recompile step (one of the features of Spring which is a nice to have). I can see Groovy filling this role very nicely, and with strong XML and SQL integration, it would be pretty easy to write a suite of configurators that took their cues from databases or XML files too.
30.03.2007 23:33:14

komik a écrit :

THansk you all
07.06.2007 14:35:44

MP3 Man a écrit :

Nice job!
20.11.2007 17:44:25

Animesh a écrit :

It seems that constructor injection is not working, because Groovy probably generates a no-arg constructor (or does it not). Guice complains because constructor injection can only work when there is only one constructor and it has an @Inject tag. Is there a workaround?
05.11.2008 12:28:49

Animesh a écrit :

My problem was actually related to Intellij Idea not properly compiling Groovy classes. Its kind of inconsistent. Anybody else has seen that. I guess I'll be better off sticking to ant.
25.01.2009 20:17:27

rolex a écrit :

20.01.2010 04:31:03

rolex a écrit :

20.01.2010 16:51:52

rolex a écrit :

23.01.2010 19:51:44

replica watches a écrit :

24.01.2010 12:43:30

nfl jersey a écrit :

29.01.2010 03:31:49

replica watches a écrit :

30.01.2010 00:12:53

replica watches a écrit :

The dial design a 100% copy http://www.watchvisa.com/ of the previous model: the famous Manchester Logo is http://www.watchvisa.com/ro... located at 3 and the chronograph 45-minute at 9 with orange figures. Football fans can use the very special 45-minute chronograph to measure the halves of a football match. Black hour replica watches hand and rolex watches minute hand breitling watches http://www.watchvisa.com/ca... features yellow luminescent cartier watches coating. http://www.watchvisa.com/om... The hour makers, chronograph and the first 15-minute http://www.watchvisa.com/br... scale of the chronograph counter is omega watches presented in eye-catching red. http://www.watchvisa.com/ta... Bright Yellow tones are found on the minute track, date window and the text tag heuer watches.<br/>
02.02.2010 13:08:23

replica watches a écrit :

03.02.2010 11:25:30

tag heuer watches a écrit :

Wearing Hamilton http://www.overwatches.com/ is not the replica watches privilege for the personnel of the railway company at that time. The inspectors of http://www.overwatches.com/... railroad, even rolex watches the company workers were its potential customers. As the development of the company, the Hamilton watch company is improving itself to being perfect. Till now, it has successfully become a top watch brand which is http://www.overwatches.com/... madly loved tag heuer watches across the world.At this point, Hamilton watch company, along with the tag heuer Watches other American cartier watch makers, decided to http://www.overwatches.com/... start producing breitling wristwatches. These were further used by the train engineers and in general, by the railroad personnel. In January 1957, this watch manufacturer http://www.overwatches.com/... launched the omega watches world's first electric wristwatch. As it was a premiere, this shocked the industry quite a bit. The battery was said to offer a power http://www.overwatches.com/... reserve of one men's watches year. In these conditions, the mainspring became useless.Hamilton Watch Company represented one of the solutions. By supplying railroad companies with amazingly accurate timepieces, the http://www.overwatches.com/... Hamilton women's watch helped to save countless lives. What also helped was the adoption of a standard time plan. The four time zones, namely Eastern, Central, Mountain and Pacific were set up. The Hamilton timepieces also played an important role in http://www.overwatches.com/... railroad safety at that ladies time. As a proof of this stands the fact that the Hamilton watch was called "The Watch of Railroad Accuracy. The book published by the Hamilton Company recorded all its historical issues. Detailed description about the models and relative data of Hamilton watches are marked inside. For those who are about to buy a Hamilton watch, this book is really worthy of reading. It can certainly help you to make the right choice.
04.02.2010 09:28:15

Rolex replica a écrit :

<a href="http://www.patekphilippewat... watches</a>
<a href="http://www.patekphilippewat... watches</a>
<a href="http://www.patekphilippewat... watches</a>
<a href="http://www.patekphilippewat... watches</a>
<a href="http://www.patekphilippewat... watches</a>
04.02.2010 10:05:27

tag heuer watches a écrit :

Roger Dubuis http://www.watchvisa.com/ro... is rolex watches a watch brand http://www.watchvisa.com/ta... which owns tag heuer watches many fans all over the world for the past years. That is because it is a watch brand with a reputation for creating seductive and innovative timepieces. By applying the most advanced technology, http://www.watchvisa.com/br... Roger Dubuis has breitling watches proven itself to be one of the most reliable brands in the watch making industry. This watch brand is a successful one by creating http://www.watchvisa.com/om... great timepieces omega watches.Roger Dubois has as a declared philosophy the intention to create highly individual timepieces, stating that Roger Dubuis represents a unique identity code. So far, Roger Dubuis has http://www.watchvisa.com/ca... managed to cartier watches fulfill all the requirements of a society interested in acquiring unique timepieces and its creations reflect passion for good taste, seductive design and high-end technical know how.Discover the power of curves with the new Roger Dubuis Excalibur Mens watch, with its interesting almost hexagonal case made of stainless Replica watches steel. Even though it replica approaches a sportier http://www.watchvisa.com/ appearance replica watches, the quality of the materials used is indisputable and the over all design of this timepiece is impressive. The case measures 43 mm in diameter, being quite masculine and it is covered with scratch resistant sapphire crystal. Also, surrounding the case we can see a unidirectional bezel made of white golf that's inscribed with Arabic numerals from 10 to 60, meant to help at diving.Belonging to the Easy Driver series, this watch was designed especially for the active men who are not afraid of exploring the depths of the oceans, as the new Roger Dubuis Excalibur Mens watch provides a water resistance of 1000 meters. Its automatic movement is quite impressive and it's defined by the designers from Roger Dubuis as the RD 14 Clibre.
04.02.2010 14:20:25

replica watches a écrit :

04.02.2010 21:17:34

replica watches a écrit :

06.02.2010 22:20:34

Ajouter un commentaire

:

:
:


Références externes

Cette page a été vue 13577 fois.
Dernier visiteur le 2010-02-09 21:18:25.