Google Guice, A Java Dependency Injection Framework

Home

News: Google Guice, A Java Dependency Injection Framework

  1. Google has announced the open source release of its internal Java dependency injection framework, Guice. Guice, pronounced 'juice', wholly embraces annotations and generics, thereby enabling you to wire together and test objects with ease. Annotations finally free you from error-prone, refactoring-adverse string identifiers. Guice injects constructors, fields and methods (any methods with any number of arguments, not just setters). Guice includes advanced features such as custom scopes, circular dependencies, static member injection, Spring integration, and AOP Alliance method interception, most of which you can ignore until you need it. An earlier version of Guice already powers Struts 2's plugin architecture. Google has been running Guice in mission critical applications for months, and now you can, too. Guice lives at Google Code. From there, you'll find the user's guide, Javadocs, and download. Please direct any questions to the mailing list.

    Threaded Messages (110)

  2. Guice v Spring[ Go to top ]

    I'll suspend my judgment on 'do we need another Dependency Injection framework?' Anybody got a summary on how this stacks up Vs something like Spring? It may have Google behind it to give it momentum, but is it worth investing time in this? Paul , Technology in Plain English
  3. To answer my own question ....[ Go to top ]

    To answer my own question , there is a Guice v Spring comparison, on the Google website: http://code.google.com/p/google-guice/wiki/SpringComparison The main difference that I can see it that Guice aims to be more simple than Spring (for good and for bad), with an emphasis on annotations rather than XML. Paul , Technology in Plain English
  4. Tapestry IoC[ Go to top ]

    You all should read about the new Tapestry IoC
  5. Re: Tapestry IoC[ Go to top ]

    You all should read about the new Tapestry IoC
    Hmmm...The "Why Not Spring?" rationale seems relatively weak to me.
  6. Re: Tapestry IoC[ Go to top ]



    Hmmm...The "Why Not Spring?" rationale seems relatively weak to me.
    Well you should also look at the code and give it a whirl before sentence.
  7. Re: Tapestry IoC[ Go to top ]



    Hmmm...The "Why Not Spring?" rationale seems relatively weak to me.


    Well you should also look at the code and give it a whirl before sentence.
    I'll give it a whirl when projects like DWR, XFire, ActiveMQ, etc. come with Guice integration out of the box, and developers are just as familiar with it as they are with Spring. Anyone want to take bets that Guice gets Biled?
  8. Spring vs Guice[ Go to top ]

    I'll give it a whirl when projects like DWR, XFire, ActiveMQ, etc. come with Guice integration out of the box, and developers are just as familiar with it as they are with Spring.

    Anyone want to take bets that Guice gets Biled?
    I don't think such an idea is that ridiculous. I think the thing that would stop me from using Guice annotations inside of XFire/CXF is that it would force us to have a hard dependency on Guice. The nice thing about XML is that it can be completely isolated in its own module. So those that want to use spring can and those that don't want to use it don't have to. Though an APT based approach could possibly work where XML files were generated. But Bruce's comments do resonate with me. In particular I'm finding the performance of Spring to be less than ideal. (Maybe I should bring out the profiler one of these days...).
  9. Re: Spring vs Guice[ Go to top ]

    Hey, Dan!
    I think the thing that would stop me from using Guice annotations inside of XFire/CXF is that it would force us to have a hard dependency on Guice.
    You can enable your users to use Guice without depending directly on Guice yourself. For example, Guice comes with a Struts 2 plugin which enables Struts 2 users to use Guice independent of Struts 2's internal Guice usages. Struts 2 uses Guice internally, but they repackage it. That said, what specifically bothers you about having a hard dependency on Guice? I can imagine a few usage scenarios, each of which has different solutions.
    But Bruce's comments do resonate with me. In particular I'm finding the performance of Spring to be less than ideal. (Maybe I should bring out the profiler one of these days...).
    Please do. :) Bob
  10. Re: Spring vs Guice[ Go to top ]

    I think the thing that would stop me from using Guice annotations inside of XFire/CXF is that it would force us to have a hard dependency on Guice. The nice thing about XML is that it can be completely isolated in its own module.
    Not sure I follow. Whether your configuration is defined in XML or with annotations, you will have a dependency on the code that parses it. There is no way around that. -- Cedric
  11. Re: Spring vs Guice[ Go to top ]

    Not sure I follow.

    Whether your configuration is defined in XML or with annotations, you will have a dependency on the code that parses it.

    There is no way around that.

    --
    Cedric
    That statment may hold for a small, well-implemented testing library, but it does not for enterprise development. Out of tens of thousands of classes in the environment I work in, only a small handful of (isolated) bootstrap classes have any dependency on the Spring framework. Doing that you describe with Guice would require thousands of interfaces to have a hard dependency on Guice (not that they would compile anyway, as I describe above). The only reason I was even able to introduce Spring into this environment was because of the non-invasive nature of the library. The lifespan of this codebase will be at least two decades, and for anyone to assume that Spring, Guice, or any other framework will be the last configuration framework ever used is ridiculous.
  12. Re: Spring vs Guice[ Go to top ]

    I think the thing that would stop me from using Guice annotations inside of XFire/CXF is that it would force us to have a hard dependency on Guice. The nice thing about XML is that it can be completely isolated in its own module.

    Not sure I follow.

    Whether your configuration is defined in XML or with annotations, you will have a dependency on the code that parses it.

    There is no way around that.

    --
    Cedric
    But at least an external metadata format allow your code to have zero dependency on the framework. You can choose the way you want to build your objects : manually or using an IoC container. It's has a lot of uses IMO. For instance, I once had to develop some organization common components which had to be usable by application not willing to use Spring (and therefore not willing to include the jars). It can also be quite pratical for long lived applications wanting the core business logic to depend on no framework. Just my two cents. And BTW guys (and girls :-)), Spring metadata != XML. You have the possibility to wire everything using Java.
  13. Re: Spring vs Guice[ Go to top ]

    Spring metadata != XML. You have the possibility to wire everything using Java.
    I'd just assume not write it at all, like Guice. ;)
  14. Re: Spring vs Guice[ Go to top ]

    Spring metadata != XML. You have the possibility to wire everything using Java.


    I'd just assume not write it at all, like Guice. ;)
    That's your choice but I rather have a domain model not coupling bean wiring and class definition in the same source file (unless there is some way to override the default wiring), even at the cost of some little extra work. BTW I don't care about being able to change a given implementation at runtime without recompiling. It's not the reason I'm prefering an external format over annotations. As many people here, I believe that when you perform those kind of changes, you should always do a full rebuild of your project. Actually, what I care about is being able to separate those two very different concepts : assembling the objects and using them. As always, it's not a black or white choice. In some cases, it's might not be worth it to define the beans wiring separatly although I definitly think that this decision shouldn't be taken lightly and most of the time my personal choice would be to externalize the wiring metadatas. Anyway good job guys, grest to see more and more great open source innovations.
  15. Biled...[ Go to top ]

    Anyone want to take bets that Guice gets Biled?
    I hope so; that alone gives it an order of magnitude more credibility.
  16. Re: Tapestry IoC[ Go to top ]



    Hmmm...The "Why Not Spring?" rationale seems relatively weak to me.


    Well you should also look at the code and give it a whirl before sentence.


    I'll give it a whirl when projects like DWR, XFire, ActiveMQ, etc. come with Guice integration out of the box, and developers are just as familiar with it as they are with Spring.

    Anyone want to take bets that Guice gets Biled?
    That's a big point. Spring has awesome support out of th box and, for me, a new comer has to match this. I do wonder how long before Guice and something like GWT oror Google maps decide to leverage each other?
  17. No Bile for Guice![ Go to top ]

    Anyone want to take bets that Guice gets Biled?
    I'll take a bet... that it doesn't get Biled. Hani Suleiman, a.k.a. Mr. Bile, is heavily involved with the Guice project. Take a look at the mailing list :)
  18. Spring can fight it out with Guice, meanwhile, Seam will be too busy competing with ASP.net to bother with Spring and Guice. Seam will be offering the full stack, from the IDE with visual editing for JSF Ajax controls, through to the server side with good conversational session management, page flows and business rules, JPA/Hibernate with EJB3, and the JBoss server, and it's all pretty much standards based. Yeah, choice is great, but at the end of the day, it's nice to sit down, write something and be productive, not spend weeks choosing which framework has a better IoC/AOP mechanism.
  19. Spring can fight it out with Guice, meanwhile, Seam will be too busy competing with ASP.net to bother with Spring and Guice.
    We like Seam. We're working with members of the Seam team on JSR 299 which I hope will standardize on many of the best features of both frameworks (and more).
  20. Yeah, choice is great, but at the end of the day, it's nice to sit down, write something and be productive, not spend weeks choosing which framework has a better IoC/AOP mechanism.
    I agree! I think that we must not concentrate about the best IoC/AOP container! I understood that DI is important, I have found a good solution, I want to use it and write my own code; and I do not want to spend many days to compare other new solutions that makes almost the same thing.
  21. Guice + Stripes = no XML hell It is nice to see simpler and adaptable frameworks coming out for Java taking full advantage of generics and annotations. I can't wait to see what closures will bring.
  22. Guice + Stripes = no XML hell

    It is nice to see simpler and adaptable frameworks coming out for Java taking full advantage of generics and annotations. I can't wait to see what closures will bring.
    I didn't see anything in the comparison that shows Guice doing anything that Spring cannot do. Spring supports Java all the way back to Java 1.3, but if you want to, you can take full advantage of autobinding and annotations. However, if you are unfortunate enough to be stuck on Java 1.3, you can STILL take full advantage of what Spring has to offer. I don't think any of the other solutions support the range of JDKs as fully and consistently as Spring.
  23. I didn't see anything in the comparison that shows Guice doing anything that Spring cannot do.
    Can Spring make itself less bloated?
  24. I didn't see anything in the comparison that shows Guice doing anything that Spring cannot do.


    Can Spring make itself less bloated?
    Well said. How is it bloated? I use Spring for AOP, DI, Transactional, and Persistence. I don't use, say, Spring MVC and it doesn't cause me a lick of trouble. Perhaps you could point me to the what you've written and enlighten all of us as to how such a framework should be written.
  25. I use Spring for AOP, DI, Transactional, and Persistence.

    I don't use, say, Spring MVC and it doesn't cause me a lick of trouble.
    I use Spring for DI, and roughly half of the 2.5M jar file contains packages that I will never use.
    ...and enlighten all of us as to how such a framework should be written.
    Probably like Guice.
  26. So what are all those support specific jars in the spring-framework\dist\modules directory for?
  27. Spring modules[ Go to top ]

    So what are all those support specific jars in the spring-framework\dist\modules directory for?
    They are for people who only want to deploy the Spring modules that are actually being used. Alternatively, you can deploy one big Spring JAR and complain about how bloated Spring is and how you only use certain pieces of it. Too bad there isn't a way to deploy Spring in a more modular fashion. Oh, wait... On a non-sarcastic note, the Guice news is exciting. I especially like the @ImplementedBy annotation. Indeed, I only find myself ever "injecting" two implementations of my service interface - the real implementation (which this annotation would configure) and a mock/stub in my test (which will be controlled my unit test). Can't wait to dig deeper.
  28. I use Spring for AOP, DI, Transactional, and Persistence.

    I don't use, say, Spring MVC and it doesn't cause me a lick of trouble.


    I use Spring for DI, and roughly half of the 2.5M jar file contains packages that I will never use.


    ...and enlighten all of us as to how such a framework should be written.


    Probably like Guice.
    Then maybe you shouldn't use spring.jar. Maybe you should use springcore.jar. I love the bloated arguments. I have documents larger than 2.5 meg. IMO, when there is nothing left to say, say something is bloated. That pitiful 2.5meg that you've forced on yourself would only exhaust a watch. Regardless, tell those poor souls still using Websphere 5 and Java 1.3, that Guice is an option. Or the many more using Java 1.5. Guice certainly has the benefit of hindsight. Heck, they pretty much admit as much. The more choices the better, but based strictly on what that site lays out, I don't see any advantages. But at least they support the AOP Alliance APIs.
  29. Spring is not bloated.[ Go to top ]

    There is a large jar file that comes with spring, which is around 2MB+. However, it is a conglomeration of much smaller, fine grained, jar files such as "spring-core", "spring-context", "spring-beans". The larger jar file is there as a convenience for when you don't care to be selective about what features you want. It's a "give me everything" jar. If you want to pick and chose your features, use the more fine grained jar files. For instance, if you want the basic bean factory capabilities of spring, just include "spring-core" and "spring-beans". If you want hibernate, add "spring-jdbc" and "spring-hibernate3-orm" to that list. It will cost you a grand total of around 600K of disk space (with the 2.0 release) to get the container and hibernate 3 support. Take the time to download something and see how it's distributed before you say it's bloated.
  30. Re: Spring is not bloated.[ Go to top ]

    Take the time to download something and see how it's distributed before you say it's bloated.
    The kinds of bloat I care most about are: a) The bloat that results from repeating yourself and writing a bunch of unnecessary code (whether it's XML or Java). We're not talking about shaving off a few characters here and there by writing code in Java instead of XML. Guice does away with a significant percentage of code altogether. b) APIs with low power-to-weight ratios. An API should only expose things a user needs to know about, and it should keep the number of these things to a minimum. Compare the relevant portions of the Spring Javadocs to those of Guice to see what I mean. c) Performance. Wiring objects together needn't compete with your real business logic for resources. Not so much jar size.
  31. What are we compariing here?[ Go to top ]

    The bloat that results from repeating yourself and writing a bunch of unnecessary code (whether it's XML or Java). We're not talking about shaving off a few characters here and there by writing code in Java instead of XML. Guice does away with a significant percentage of code altogether.
    I welcome anything that eliminates this "bloat".
    APIs with low power-to-weight ratios. An API should only expose things a user needs to know about, and it should keep the number of these things to a minimum. Compare the relevant portions of the Spring Javadocs to those of Guice to see what I mean.
    This is little misleading. The Spring APIs cover much more than DI. Still, I get (and appreciate) your point.
    Performance. Wiring objects together needn't compete with your real business logic for resources.
    Are these really ever competing for resources? DI happens at start up time, business logic is executed at runtime. While increasing start up time is always a good thing (especially for testing) I can't see this impacting runtime performance of an application unless I am misinterpreting what you mean when you say "wiring objects". Good work.
  32. Re: What are we compariing here?[ Go to top ]

    APIs with low power-to-weight ratios. An API should only expose things a user needs to know about, and it should keep the number of these things to a minimum. Compare the relevant portions of the Spring Javadocs to those of Guice to see what I mean.


    This is little misleading. The Spring APIs cover much more than DI. Still, I get (and appreciate) your point.
    I didn't intend to mislead. That's what I meant by "relevant portions"--basically anything under the "bean" package and then some.
    Performance. Wiring objects together needn't compete with your real business logic for resources.


    Are these really ever competing for resources? DI happens at start up time, business logic is executed at runtime. While increasing start up time is always a good thing (especially for testing) I can't see this impacting runtime performance of an application unless I am misinterpreting what you mean when you say "wiring objects".
    DI only happens purely at startup when you use singletons for everything. If that's the case in your application, then you can ignore performance (unless, as you point out, you care about startup performance, too).
  33. Re: Spring is not bloated.[ Go to top ]

    Take the time to download something and see how it's distributed before you say it's bloated.


    The kinds of bloat I care most about are:

    a) The bloat that results from repeating yourself and writing a bunch of unnecessary code (whether it's XML or Java). We're not talking about shaving off a few characters here and there by writing code in Java instead of XML. Guice does away with a significant percentage of code altogether.

    b) APIs with low power-to-weight ratios. An API should only expose things a user needs to know about, and it should keep the number of these things to a minimum. Compare the relevant portions of the Spring Javadocs to those of Guice to see what I mean.

    c) Performance. Wiring objects together needn't compete with your real business logic for resources.

    Not so much jar size.
    Well, I haven't had any problems with wiring, but our apps aren't large. The XML allows you to inherit definitions and like Tiles, and they've trimmed them down even further in Spring 2.0. Personally, I've never found the XML to be a big deal, but that's me. As for the APIs, I'm not sure what you mean. An example perhaps?
  34. Re: Spring is not bloated.[ Go to top ]

    Kind of silly way of comparing. The link to the javadocs actually prooves the point: that you are comparing some dressing with a whole meal. You normally compare things which are built with the same goals and intention adressing similiar requirements. Well, you certainly can compare a car like Smart with a Van? But only to find out, that the Van was'nt made to adress your requirements. That's fairly trivial. We use Spring. DI is only a means to what we want from Spring: a configurable, unobstrusive Fassade to J2EE based Resources, a means to standardize the way we use them. Configuration is only one aspect. BTW: Our business logic doesn't know at all of Spring. Seems funny to think it should.
  35. Re: Spring is not bloated.[ Go to top ]

    Kind of silly way of comparing. The link to the javadocs actually prooves the point: that you are comparing some dressing with a whole meal.
    As I already said, take everything under the "bean" package (and then some). I would have linked directly to the bean package summary, but you wouldn't be able to see the child packages.
  36. Re: Spring is not bloated.[ Go to top ]

    Take the time to download something and see how it's distributed before you say it's bloated.


    The kinds of bloat I care most about are:

    a) The bloat that results from repeating yourself and writing a bunch of unnecessary code (whether it's XML or Java). We're not talking about shaving off a few characters here and there by writing code in Java instead of XML. Guice does away with a significant percentage of code altogether.

    b) APIs with low power-to-weight ratios. An API should only expose things a user needs to know about, and it should keep the number of these things to a minimum. Compare the relevant portions of the Spring Javadocs to those of Guice to see what I mean.

    c) Performance. Wiring objects together needn't compete with your real business logic for resources.

    Not so much jar size.
    a) I fiercly advocate autowiring, because it's 100% convention-over-configuration, and reduces the dependency expression to a single point: the setter (or the constructor). Using JavaBean conventions actually require less configuration than annotations: @Inject public Client(Service service) { ... } binder.bind(ServiceImpl.class).to(Service.class); versus (with autowiring-by-constructor in this case): public Client(Service service) { ... } b) I agree that it would be nice if Spring hid internal parts in the Javadocs, but those two links aren't exactly a fair comparision, since Spring does about 100 times more than Guice. Of course the javadoc index will be larger. c) Guice is fast, way faster than Spring (I've run the benchmark). However, in a real-world situation, how much time is spent on IoC versus for example setting up a Hibernate SessionFactory? Making 5% of the application startup time 50 times faster only yields an 4.9% overall cut (0.05/50 + 0.95 == 0.951). On computer where I'm currently working, Spring creates ~6k object graphs per second and Guice ~300k, but a medium size application needs what, 500? That's still in the tenths-of-a-second range, even for Spring.
  37. Re: Spring is not bloated.[ Go to top ]

    I fiercly advocate autowiring, because it's 100% convention-over-configuration, and reduces the dependency expression to a single point: the setter (or the constructor).
    This may work OK for small applications, but it doesn't scale. You're the first Spring user I've found who actually advocates auto-wiring wholesale. Perhaps you haven't had to maintain much auto-wiring code or your application isn't very big?
    Guice is fast, way faster than Spring (I've run the benchmark). However, in a real-world situation, how much time is spent on IoC versus for example setting up a Hibernate SessionFactory? Making 5% of the application startup time 50 times faster only yields an 4.9% overall cut (0.05/50 + 0.95 == 0.951). On computer where I'm currently working, Spring creates ~6k object graphs per second and Guice ~300k, but a medium size application needs what, 500? That's still in the tenths-of-a-second range, even for Spring.
    Our application constantly creates object graphs. Do you use singletons for everything? At the very least you can't use them for request and session scoped objects.
  38. Re: Spring is not bloated.[ Go to top ]

    I fiercly advocate autowiring, because it's 100% convention-over-configuration, and reduces the dependency expression to a single point: the setter (or the constructor).


    This may work OK for small applications, but it doesn't scale. You're the first Spring user I've found who actually advocates auto-wiring wholesale. Perhaps you haven't had to maintain much auto-wiring code or your application isn't very big?

    In this crowd, I'd say I've mostly worked on small-to-medium sized projects, mostly three tier applications with around 20 domain entities, daos, services etc, and maybe twice as many controllers. All of which autowired. Sure, they're not online banks, but in my opinion autowiring scales _better_ than explicit wiring, since the amount of configuration doesn't explode when the number of components grow. I really think that the relations expressed in the Java source code is enough, that's where I go to look for that kind of information, not applicationContext.xml. Besides, autowiring is overridable on bean or property basis.
    Guice is fast, way faster than Spring (I've run the benchmark). However, in a real-world situation, how much time is spent on IoC versus for example setting up a Hibernate SessionFactory? Making 5% of the application startup time 50 times faster only yields an 4.9% overall cut (0.05/50 + 0.95 == 0.951). On computer where I'm currently working, Spring creates ~6k object graphs per second and Guice ~300k, but a medium size application needs what, 500? That's still in the tenths-of-a-second range, even for Spring.


    Our application constantly creates object graphs. Do you use singletons for everything? At the very least you can't use them for request and session scoped objects.
    Yes, I use singletons for everything. I can see the importance of high performance if you rely heavily on request-scoped objects, and have very high volumes of traffic (as I suspect that Google has :-) )
  39. Re: Spring is not bloated.[ Go to top ]

    I fiercly advocate autowiring, because it's 100% convention-over-configuration, and reduces the dependency expression to a single point: the setter (or the constructor).


    This may work OK for small applications, but it doesn't scale. You're the first Spring user I've found who actually advocates auto-wiring wholesale. Perhaps you haven't had to maintain much auto-wiring code or your application isn't very big?



    In this crowd, I'd say I've mostly worked on small-to-medium sized projects, mostly three tier applications with around 20 domain entities, daos, services etc, and maybe twice as many controllers. All of which autowired. Sure, they're not online banks, but in my opinion autowiring scales _better_ than explicit wiring, since the amount of configuration doesn't explode when the number of components grow. I really think that the relations expressed in the Java source code is enough, that's where I go to look for that kind of information, not applicationContext.xml. Besides, autowiring is overridable on bean or property basis.

    Guice is fast, way faster than Spring (I've run the benchmark). However, in a real-world situation, how much time is spent on IoC versus for example setting up a Hibernate SessionFactory? Making 5% of the application startup time 50 times faster only yields an 4.9% overall cut (0.05/50 + 0.95 == 0.951). On computer where I'm currently working, Spring creates ~6k object graphs per second and Guice ~300k, but a medium size application needs what, 500? That's still in the tenths-of-a-second range, even for Spring.


    Our application constantly creates object graphs. Do you use singletons for everything? At the very least you can't use them for request and session scoped objects.

    Yes, I use singletons for everything. I can see the importance of high performance if you rely heavily on request-scoped objects, and have very high volumes of traffic (as I suspect that Google has :-) )
    I work on similar sized applications. Usually 2 or 3 per year. I still prefer the explicit wiring. I've standardized the xml to basically multiple XML files based on layer and function. For example, I've recently introduced a filters.xml that handles Spring-managed servlet filters or cache-management or caching configuration. I'ved used this setp for apps as small as two pages. I've found that the consistency across all apps, makes up for the overhead even for very small apps. Someone can look at a small app and understand our larger versions.
  40. I tried to sum up how Guice can make your configuration cleaner here. Can you do autobinding in Spring? By autobinding I mean: @ImplementedBy(FooManagerImpl.class) public interface FooManager() {...} @Singleton public class FooManagerImpl implements FooManager() {...} public class FooAction { @Inject public void setFooManager(FooManager fooManager) {...} } And then Guice wires up the FooManager dependency into FooAction without any external configuration in Java or XML necessary. Can you do that with Spring?
  41. I tried to sum up how Guice can make your configuration cleaner here.

    Can you do autobinding in Spring? By autobinding I mean:

    @ImplementedBy(FooManagerImpl.class)
    public interface FooManager() {...}
    This may not be the best example of using DI with annotations. The whole purpose of DI is lost if I need to recompile (and repackage) my code just if I need to change my implementation class.

    @Singleton
    public class FooManagerImpl implements FooManager() {...}
    Again a matter of convenience and concerns whether one would like to have instance management hard-coded in the code or externally configurable. A singelton is an exception, but I would definitely not prefer to have something like: @PoolSize=5 in my code.
  42. A singelton is an exception, but I would definitely not prefer to have something like:

    @PoolSize=5

    in my code.
    Presumably you'd use the annotation as a default which you can override in the XML config. That's how Seam does it anyway.
  43. A singelton is an exception, but I would definitely not prefer to have something like:

    @PoolSize=5

    in my code.


    Presumably you'd use the annotation as a default which you can override in the XML config. That's how Seam does it anyway.
    personally, i'd rather it not start up in the first place without a proper configuration
  44. This may not be the best example of using DI with annotations. The whole purpose of DI is lost if I need to recompile (and repackage) my code just if I need to change my implementation class.
    The "whole purpose of DI" is to me to manage the assumptions I make about the code in as few places as possible. If one assumption I make is that an interface is going to be backed by a particular implementation, then I don't see a major problem with that. There are more reasons to use interface/impl separation than just the ability to switch implementations. In my own code roughly 97-99% of all interfaces have only one implementation, so for me that style of annotations would work just fine in most cases. But I'm curious, those who are seemingly outraged with this annotation, is it really that common for you to have multiple impls of an interface? Can you outline the usecases that you have? I would be most interested in hearing about them.
  45. This may not be the best example of using DI with annotations. The whole purpose of DI is lost if I need to recompile (and repackage) my code just if I need to change my implementation class.

    The "whole purpose of DI" is to me to manage the assumptions I make about the code in as few places as possible. If one assumption I make is that an interface is going to be backed by a particular implementation, then I don't see a major problem with that. There are more reasons to use interface/impl separation than just the ability to switch implementations. In my own code roughly 97-99% of all interfaces have only one implementation, so for me that style of annotations would work just fine in most cases.

    But I'm curious, those who are seemingly outraged with this annotation, is it really that common for you to have multiple impls of an interface? Can you outline the usecases that you have? I would be most interested in hearing about them.
    Outraged, I think is strong. I prefer choice. I prefer being able to choose what I want. If Guice supports both, then why is the annotation being herald by some as such an innovation. Regardless, there have been times when I've used the ability to make changes to the app(turning on/off profiling, caching, security, transaction and change certain implementations) by simply changing the XML and restarting the app. I can do this now, so I'm relunctant to give this up. That being said, some items are good for annotations because they rarely change. The config of my persistence layer changes rarely once it is in place, so I only externalize db host, user, pass, etc.
  46. Outraged, I think is strong. I prefer choice. I prefer being able to choose what I want. If Guice supports both, then why is the annotation being herald by some as such an innovation.
    I'm not sure you understood my question, but I wasn't referring to annotations in Guice in general, but rather the specific idea to annotate interfaces with the name of the implementation. Configuration things like ports and such are fine to put in XML files, but as I said, it is extreeeemely rare in my own apps anyway that I want to replace one impl with another. In fact, in my own case the number of times I have wanted to do that is zero. So, for myself that annotation would work wonders.
  47. it is extreeeemely rare in my own apps anyway that I want to replace one impl with another. In fact, in my own case the number of times I have wanted to do that is zero.
    Rickard, I have seen your code. I frequently use the command pattern (which always involves multiple impls for me), and have gotten pretty effective at it by reading the code of open-source developers such as yourself. You've changed, man. You used to be about the abstraction.
  48. Rickard, I have seen your code. I frequently use the command pattern (which always involves multiple impls for me), and have gotten pretty effective at it by reading the code of open-source developers such as yourself.

    You've changed, man. You used to be about the abstraction.
    Right, and I still am. But between then and now I have also been subjected to a healthy dose of reality, and reality is that too much abstraction will make you go blind. I have had to do LOTS of tricks in our AOP framework to make it LESS abstract, and it's still not good enough. Whenever you make an abstraction you have to understand that you are creating a contract that someone has to take time to understand. Sometimes it is worth it, and sometimes not, and only history can give you an answer to the question of when it is right to do what. But if there's a whole bunch of interfaces which will only ever have one implementation then I don't have a problem making that relation explicit. Ask me again in ten years and I might say the contrary though. Who knows. But is this the same way as saying that ALL interfaces should ALWAYS have this? Of course not. The problem seem to be that some people have a really hard time understanding the word "sometimes", and instead think in black and white terms. That is counterproductive and, I think, simply unnecessarily limits ones ability to reason about these things.
  49. Right, and I still am. But between then and now I have also been subjected to a healthy dose of reality, and reality is that too much abstraction will make you go blind. I have had to do LOTS of tricks in our AOP framework to make it LESS abstract, and it's still not good enough.
    No doubt. You must sacrifice abstraction for performance when you are writing an MVC framework, or an AOP framework. When you are working on a large codebase, that will be touched by the unwashed masses over many years, abstraction is king. It is the only shot you have at ensuring the code lasts over time. For non-realtime systems, you can solve any such performance issues by having the corporate overlords purchase more hardware. Just to reiterate, I do not object to all uses of @ImplementedBy. I do object to using it in an application's core business-logic, as was cited in an example earlier.
    Whenever you make an abstraction you have to understand that you are creating a contract that someone has to take time to understand.
    Not as much time as it requires them to understand the implementation.
  50. No doubt. You must sacrifice abstraction for performance when you are writing an MVC framework, or an AOP framework.
    Not really, I could get decent performance with good abstractions, and sometimes good abstractions helped increase performance. The problem was rather that since AOP by nature is "magical" I had to really focus on minimizing the number of abstractions so that one did not get a headache whenever you create an AOP object or interceptor. That is the difficult part, and which noone has really solved satisfactorily yet in the AOP space, including myself.
    When you are working on a large codebase, that will be touched by the unwashed masses over many years, abstraction is king.
    And it can also be a "good" way to ensure that noone touches the codebase at all, for fear of breaking any abstractions. I've seen that happening... "this is so abstract that I have no idea how to create my own implementation of it".
    It is the only shot you have at ensuring the code lasts over time.
    Which, as above, may sometimes mean that it does not evolve and is therefore longlasting. Rocks last a long time too, but they also make terrible material for making furniture as they are too rigid. The devil is always in the details.
  51. When you are working on a large codebase, that will be touched by the unwashed masses over many years, abstraction is king.
    Wow! Do you really think so? How about a large codebase that incorporates a factory pattern all over the places that return implementation classes via Class.forName( defined in property files ) and all that with exactly zero use cases when an interface has more than one implementation. Let me assure you that this kind of abstraction is VERY painful to deal with. By the way: decent IDEs allow to extract interface from class and refactor code to use the interface. So, nowadays there is no reason to define interface - implementation pair if there is no immediate need to do so. Interfaces can be introduced later ond only if they are needed. Simplicity is the king - and simplest thing that works is the class :)
  52. How about a large codebase... with exactly zero use cases when an interface has more than one implementation.
    I will not doubt you if you say so, but I will just say that the existence of such a thing would surprise me greatly, and I would find it highly unusual. Or perhaps we disagree on the meaning of large. In any event, I cited examples above of why you still might want to use interface-implementation abstraction in such a case.
    So, nowadays there is no reason to define interface - implementation pair if there is no immediate need to do so.
    Certainly. And if you are going the @ImplementedBy route, you can ditch the interfaces and the Guice, and implement everything as public static methods. (yes, this is illustrative hyperbole) However, I find interfaces to be an excellent communication tool for people who don't know every line of the codebase (all of us). It is much easier to peruse the interface than the implementation, and it tends to work out better if the original developer is creating the abstraction, rather than someone later who is attempting to learn the code for the first time.
  53. I will not doubt you if you say so, but I will just say that the existence of such a thing would surprise me greatly, and I would find it highly unusual. Or perhaps we disagree on the meaning of large.
    It has probably more to do with how we deal with differences between customers. In our case we do it by making fine-grained configurations and scripting. Those two tools are enough to handle the wide variety of customers we have that use our CMS, without having to mess with particular implementations. But certainly, if this is enough or not will be highly dependent on the actual case.
  54. So, nowadays there is no reason to define interface - implementation pair if there is no immediate need to do so. Interfaces can be introduced later ond only if they are needed.
    Hope it worked for you, because i can't assure that. My experience is that the team needs the level of indirection that an interface provides between client and implementation to collaborate, isolating a class (implementation) and develop it providing mock or test colaborators. Its not just simple... :P
  55. So, nowadays there is no reason to define interface - implementation pair if there is no immediate need to do so.
    Maybe so, but most of the objects I wire together are service/infrastructure objects. Theses object tend to collaborate with similar objects. As these dependencies emerge during development, the need for an interface/implementation pair arises a soon as I begin writing tests. So, I rarely *don't* need an interface/implementation pair. For most business/persistance services I develop, it really is usually a pair - Service/ServiceImpl or CustomerDao/HibernateCustomerDao. In this case, defining a default implementation makes sense and I can see how annotations may simplify configuration. However, for classes that interact with other third party APIs, I often don't know the runtime implementation and I can't assume a default implementation (e.g. writing a decorator for an HttpServletRequest). In these cases, I have to rely on external binding.
  56. But between then and now I have also been subjected to a healthy dose of reality, and reality is that too much abstraction will make you go blind. I have had to do LOTS of tricks in our AOP framework to make it LESS abstract, and it's still not good enough. Whenever you make an abstraction you have to understand that you are creating a contract that someone has to take time to understand.
    Interesting. I agree more abstractions lead to greater training and ramp up time - but I've consistently observed lower time and effort in using them. I have had to do LOTs of tricks in the implementations of our abstractions to sometimes make them perform really well, but haven't really had to cut down on the abstractions (This is in a platform with more than 1000 interfaces).
    Sometimes it is worth it, and sometimes not, and only history can give you an answer to the question of when it is right to do what.
    In my experience the cost of each interface that needs to be subsequently refactored in a way that breaks backward compatibility is a lot of "Oh No! Not Again" (not that we do it too often) which is really expensive in terms of developer dissatisfaction.
    But if there's a whole bunch of interfaces which will only ever have one implementation then I don't have a problem making that relation explicit.
    In our context I do. I have at times turned over the implementation code to another development team a year or more down the road after the initial implementation had been developed to allow them to tweak the implementation to their specific requirements - even though I might I have thought of, planned for, and designed for only one implementation.
  57. it is extreeeemely rare in my own apps anyway that I want to replace one impl with another. In fact, in my own case the number of times I have wanted to do that is zero.


    Rickard, I have seen your code. I frequently use the command pattern (which always involves multiple impls for me), and have gotten pretty effective at it by reading the code of open-source developers such as yourself.

    You've changed, man. You used to be about the abstraction.
    I agree with Rickard's observations. Actually, the class is the abstraction. Just because it can also be the implementation doesn't change that fact. In the client code you still lookup the service(or inject it) via the class definition. Just because it is not an interface class per se doesn't mean you are breaking abstraction.
  58. Outraged, I think is strong. I prefer choice. I prefer being able to choose what I want. If Guice supports both, then why is the annotation being herald by some as such an innovation.

    I'm not sure you understood my question, but I wasn't referring to annotations in Guice in general, but rather the specific idea to annotate interfaces with the name of the implementation. Configuration things like ports and such are fine to put in XML files, but as I said, it is extreeeemely rare in my own apps anyway that I want to replace one impl with another. In fact, in my own case the number of times I have wanted to do that is zero. So, for myself that annotation would work wonders.
    I understood you perfectly. As I stated, I've changed implemenations. There were times when I needed to see how two implementations behaved in a production environment. A change to the XML was all I needed. Similarly, as I stated, I have changed transactions, profiling, security, and caching all through XML changes. Annotations would have required recompiles.
  59. DI without XML[ Go to top ]

    The "whole purpose of DI" is to me to manage the assumptions I make about the code in as few places as possible.
    That is exactly right IMO, and well said. Additionally, the case where that information must be changeable without the need to recompile is only where you plug into a binary runtime system (AKA container), or want to provide such binary pluggable interfaces. Using non-compiled formats like XML in any other cases is a major productivity and maintenance setback.
  60. This may not be the best example of using DI with annotations. The whole purpose of DI is lost if I need to recompile (and repackage) my code just if I need to change my implementation class.

    The "whole purpose of DI" is to me to manage the assumptions I make about the code in as few places as possible. If one assumption I make is that an interface is going to be backed by a particular implementation, then I don't see a major problem with that. There are more reasons to use interface/impl separation than just the ability to switch implementations. In my own code roughly 97-99% of all interfaces have only one implementation, so for me that style of annotations would work just fine in most cases.

    But I'm curious, those who are seemingly outraged with this annotation, is it really that common for you to have multiple impls of an interface? Can you outline the usecases that you have? I would be most interested in hearing about them.
    Rickard, Hearing this ridiculous ideas from you, I'm glad you didn't design the JDK. Because then you'll force me to write code like ArrayList list = new ArrayList(), instead of List list= new ArrayList() and hence would lose all the flexibility that the latter opens up. Jan
  61. Rickard,

    Hearing this ridiculous ideas from you, I'm glad you didn't design the JDK. Because then you'll force me to write code like ArrayList list = new ArrayList(), instead of List list= new ArrayList() and hence would lose all the flexibility that the latter opens up.

    Jan
    "You think like this and this, and you are therefore stupid". That would be "projection", or the "straw man argument", if I'm not entirely mistaken. Please don't tell me what I think, and I won't tell you what you think. Fair enough?
  62. Rickard,

    Hearing this ridiculous ideas from you, I'm glad you didn't design the JDK. Because then you'll force me to write code like ArrayList list = new ArrayList(), instead of List list= new ArrayList() and hence would lose all the flexibility that the latter opens up.

    Jan


    "You think like this and this, and you are therefore stupid". That would be "projection", or the "straw man argument", if I'm not entirely mistaken.

    Please don't tell me what I think, and I won't tell you what you think. Fair enough?
    At least that was a very basic example to wake you up :-). Are you warmed up now? Ok, mission accomplished! Back to coding. Regards, Jan
  63. But I'm curious, those who are seemingly outraged with this annotation, is it really that common for you to have multiple impls of an interface? Can you outline the usecases that you have? I would be most interested in hearing about them.
    On top of what David said, an every-day usecase for me is that I need to quickly run a modified form of a process during iterative development. Assume that my CheckoutProcessImpl has the following method: public void checkout() { validateCustomer(); validatePayment(); postTransaction(); } I need to quickly run a large process that executes my code, but skips the validatePayment() step for one reason or the other. I quickly dummy up two files that are not part of the main source tree. dummyContext.xml DummyCheckoutProcess_Impl extends CheckoutProcess_Impl public void checkout() { validateCustomer(); postTransaction(); } Now, I run a modified version of the complete application without touching any of the core source. This is important during an ongoing development process because when it comes time to check-in, I don't have to go through the error-prone process of preserving the changes I want to keep, while backing out the changes I made for development purposes. Not to mentioned the Guicey interface that was shown earlier would not even compile in my enterprise environment. Once you have tens of thousands of classes in an application, it is common for interfaces to be stored in their own module that is not dependent on the module where the implementations reside. This is a frequent build optimization. Finally, expecting people to put Guice annotations in the most common interfaces reeks of hubris. It says Guice is the last framework, and you will never need another framework for configuring your core business components. I hope I don't have to spell out how silly that is. To be clear, I am not slamming Guice. Using Guice in Struts 2 is a great sweet spot, it enables super-fast injection of stateful components, and its use is hidden from the end-user. But people who are saying Guice is a good idea for general enterprise development rank up there with the people who said Rails would have displaced Java by now.
  64. Now, I run a modified version of the complete application without touching any of the core source. This is important during an ongoing development process because when it comes time to check-in, I don't have to go through the error-prone process of preserving the changes I want to keep, while backing out the changes I made for development purposes.
    Yup, that definitely seems like a valid usecase. But then it sounds like there is a default that you want to override for a moment. For this you could temporarily replace your Guice "bind(MyAnnotatedInterface.class)" with "bind(MyAnnotatedInterface.class).to(DummyMyInterfaceImpl.class)" In other words, just because there is an annotation on the interface for the default it should not prevent you from doing an explicit override. Implicit defaults and explicit overrides. This, by the way, as an example of my design philosophy, is the same reason the XML configs in WebWork/Struts2 look the way they do, with base confs that you can inherit and/or override.
    Not to mentioned the Guicey interface that was shown earlier would not even compile in my enterprise environment. Once you have tens of thousands of classes in an application, it is common for interfaces to be stored in their own module that is not dependent on the module where the implementations reside. This is a frequent build optimization.
    This is a very much valid concern I think, and I had the same objection what I discussed this feature with Bob earlier (yes, I had a small finger in getting this annotation in there). Especially now that we're getting all OSGi'fied with module classloaders and whatnot it becomes very important to think about classloader dependencies. Another way to look at this interface/impl dependency is of course to do it the other way round and bind the impl instead and assume that it will be exposed with its implemented interfaces as key(s), i.e. "bind(DummyMyInterfaceImpl.class)". The quesion then is whether the "magic" of having the interfaces of an object implicitly is worth it. I think there's a discussion about this on the mailing list as it happens, where Hani made a few good points.
    Finally, expecting people to put Guice annotations in the most common interfaces reeks of hubris. It says Guice is the last framework, and you will never need another framework for configuring your core business components. I hope I don't have to spell out how silly that is.
    Well, as far as I can tell putting them in there is not limiting the use of any other frameworks, so it's not getting in the way. Or am I missing something?
  65. This may not be the best example of using DI with annotations. The whole purpose of DI is lost if I need to recompile (and repackage) my code just if I need to change my implementation class.

    ... If one assumption I make is that an interface is going to be backed by a particular implementation, then I don't see a major problem with that. ..

    But I'm curious, those who are seemingly outraged with this annotation, is it really that common for you to have multiple impls of an interface? Can you outline the usecases that you have? I would be most interested in hearing about them.
    Rickard, We develop products whose deployment configurations need to be substantially tuned to suit a particular implementation. These are not shrink wrapped desktop products but large enterprise applications which require substantial customisation based on the specific requirements and the particular customer's environment. In our case the implementations need to be changed from deployment to deployment (as an example we may need to choose between multiple authentication schemes). DI helps tremendously by being able to change the implementation at deployment time. In this particular set of use cases, a majority of the interfaces which are used within the DI context have more than one implementation. Dhananjay
  66. In our case the implementations need to be changed from deployment to deployment (as an example we may need to choose between multiple authentication schemes). DI helps tremendously by being able to change the implementation at deployment time.

    In this particular set of use cases, a majority of the interfaces which are used within the DI context have more than one implementation.

    Dhananjay
    This is so innate to our environment that I completely forgot about it when I was citing examples. A very large number of our interfaces also have client-specific implementations as described by Dhananjay.
  67. We develop products whose deployment configurations need to be substantially tuned to suit a particular implementation. These are not shrink wrapped desktop products but large enterprise applications which require substantial customisation based on the specific requirements and the particular customer's environment. In our case the implementations need to be changed from deployment to deployment (as an example we may need to choose between multiple authentication schemes). DI helps tremendously by being able to change the implementation at deployment time.
    Dhananjay, Guice does support external configuration, but we don't force you to externalize everything by default. We prefer to have a manageable-sized properties file (or something along those lines) which someone who didn't actually write the code can understand. This is where Guice's constant type conversion comes in handy (your values get type checked at startup).
  68. Can you do autobinding in Spring? By autobinding I mean:

    @ImplementedBy(FooManagerImpl.class)
    public interface FooManager() {...}

    @Singleton
    public class FooManagerImpl implements FooManager() {...}

    public class FooAction {
    @Inject
    public void setFooManager(FooManager fooManager) {...}
    }

    And then Guice wires up the FooManager dependency into FooAction without any external configuration in Java or XML necessary. Can you do that with Spring?
    I don't think that's called autobinding. I think that's called the worst freaking idea in human history.
  69. I don't think that's called autobinding. I think that's called the worst freaking idea in human history.
    Why? I'm willing to concede that I might be wrong, and this might be a bad idea, but just calling it a bad idea and offering no explanation as to why provides no value to the conversation. I assume one thing people are going to say is this is a bad idea because I can't make this change without recompiling the code. That doesn't bother me. With Spring, you still have to edit the XML file, make a new WAR, deploy it and restart the app server. And the annotation still gives you dependency injection, because I can create a unit test for FooAction and set the fooManager with a mock impl of FooManager.
  70. No offense, but can you change the FooManager impl without recompiling the java class in Guice? Or, actually I didn't see any point of using such stuff here.
  71. I tried to sum up how Guice can make your configuration cleaner here.

    Can you do autobinding in Spring? By autobinding I mean:

    @ImplementedBy(FooManagerImpl.class)
    public interface FooManager() {...}

    @Singleton
    public class FooManagerImpl implements FooManager() {...}

    public class FooAction {
    @Inject
    public void setFooManager(FooManager fooManager) {...}
    }

    And then Guice wires up the FooManager dependency into FooAction without any external configuration in Java or XML necessary. Can you do that with Spring?
    Autobinding was in Spring AND Picocontainer as early as 2004(maybe even '03), I mean, are you kidding? And personally, I like the XML. I don't want to recompile when I make certain changes. With Spring, you have the option to use XML or annotations. And if you are still using JDK 1.4, you don't have any options with Guice.
  72. Autobinding was in Spring AND Picocontainer as early as 2004(maybe even '03), I mean, are you kidding?
    Guice doesn't support auto-wiring in the classic sense. Guice claims a sweet spot between explicit configuration and auto-wiring which is concise yet maintainable. From the Guice/Spring comparison: "Spring supports two polar configuration styles: explicit configuration and auto-wiring. Explicit configuration is verbose but maintainable. Auto-wiring is concise but slow and not well suited to non-trivial applications. If you have 100s of developers and 100s of thousands of lines of code, auto-wiring isn't an option. Guice uses annotations to support a best-of-both-worlds approach which is concise but explicit (and maintainable)."
    And personally, I like the XML. I don't want to recompile when I make certain changes. With Spring, you have the option to use XML or annotations.
    This is a common misconception about Guice. You can still externalize things when you want, but Guice doesn't force you to always externalize everything. If you want to choose an implementation at runtime, you could specify it in a properties file and Guice can automatically convert the string name to a Class at startup.
    And if you are still using JDK 1.4, you don't have any options with Guice.
    Yeah, Java 1.4 users are out of luck. Then again, Java 6 is already out.
  73. Autobinding was in Spring AND Picocontainer as early as 2004(maybe even '03), I mean, are you kidding?


    Guice doesn't support auto-wiring in the classic sense. Guice claims a sweet spot between explicit configuration and auto-wiring which is concise yet maintainable.

    From the Guice/Spring comparison: "Spring supports two polar configuration styles: explicit configuration and auto-wiring. Explicit configuration is verbose but maintainable. Auto-wiring is concise but slow and not well suited to non-trivial applications. If you have 100s of developers and 100s of thousands of lines of code, auto-wiring isn't an option. Guice uses annotations to support a best-of-both-worlds approach which is concise but explicit (and maintainable)."

    And personally, I like the XML. I don't want to recompile when I make certain changes. With Spring, you have the option to use XML or annotations.


    This is a common misconception about Guice. You can still externalize things when you want, but Guice doesn't force you to always externalize everything. If you want to choose an implementation at runtime, you could specify it in a properties file and Guice can automatically convert the string name to a Class at startup.

    And if you are still using JDK 1.4, you don't have any options with Guice.


    Yeah, Java 1.4 users are out of luck. Then again, Java 6 is already out.
    Just out. And tons of apps still have to use 1.4. I'll be the first to jump on 6, and actually, my next new project should be Spring, Hibernate 3, GWT, and Java 6 amongst other things. But we still have to support our 1.4 apps that use Spring. So why use both? No reason, IMO. This is not to say don't use Guice. I'm a mercenary and can be won over like that. But Guice has to be compelling. GWT is compelling next to Struts. I think Spring's potential is still going up.
  74. And if you are still using JDK 1.4, you don't have any options with Guice.
    Look at Using Java 5 language features in earlier JDKs. You can develop using Java 5 but deploy to J2SE 1.4. Taras Disclaimer: I wrote Retrotranslator
  75. Guice + Stripes = no XML hell
    The hell isn't because of using XML. It's how some people use meta-data. If those people can make a "hell" out of XML, the same guys can also turn a hell out of annotations. It's just that they haven't got their hands on it yet. Its easier to blame technology than question the techniques.
  76. Its easier to blame technology than question the techniques.
    You are right XML should not be blamed because it does not do much. Blaming XML is like blaming alphabet. And this is the root of the problem: Xtensible-Markup-Language in reality is not language at all and thus has no meaning, but because word language is present in the acronym it is marketed as if XML has some meaning and then the snowball effect: if XML is used then by definition the thing supposed to have meaning and being human readable automatically. In reality it turned ugly to the extremes like Jelly With all that being said I think that it is appropriate to blame XML assuming that "XML" stands for the whole bunch of half backed standards and even less working implementations.
  77. You are right XML should not be blamed because it does not do much. Blaming XML is like blaming alphabet.
    I agree. But XML has a few disadvantages developers should keep in mind when storing configuration or programming constructs in XML. 1. XML might be human readable, but the data (configuration/programming constructs) stored as XML might not be that readable. Designing a good XML syntax for the task is important in keeping larger data structures understandable for normal humans. Case point from ant: I think the above is a classic example of a domain specific language (DSL) implemented in XML and the syntax is a bit too verbose at least for my taste. Configuration can be seen as a sort DSL too and complex configurations might have the same problems when using XML. 2. The IDEs rarely have support for the DSL. This is getting better, but I'd still like to see a time when refactoring a class also refactors the configuration files or debugging a program with XML-DSL also debugs the XML in a native way. A good GUI editor, something which presents the data in a better way, wouldn't hurt either :) 3. Testing XML constructs might be nasty. A few files are easily controlled, but testing that a collection of 100s of XML-files behaves correctly isn't easy. 4. There's also the problem of keeping separate instances which refer to the same data structure synched. Suppose I store some configuration in format 1 in a database. If the format is updated to version v1.1, how should the changes be updated? This isn't a problem if you keep XML in jars, but sometimes it's nice to have something stored separately and dynamically updated. Anyways, congrats to Guice team for the 1.0 release. I hope this competition/co-operation in DI-field brings us better tools and saves me from writing that one extra line of configuration :)
  78. Guice + Stripes = no XML hell

    It is nice to see simpler and adaptable frameworks coming out for Java taking full advantage of generics and annotations. I can't wait to see what closures will bring.
    Closure?
  79. It is nice to see simpler and adaptable frameworks coming out for Java taking full advantage of generics and annotations. I can't wait to see what closures will bring.
    I just wish there would be some standard set of DI annotations in JRE itself and not in external lib. JSR anyone?
  80. From Spring to Guice[ Go to top ]

    If you want a third party comparison of Guice and Spring, I recommend Eric Burke's initial impressions.
  81. Re: From Spring to Guice[ Go to top ]

    If you want a third party comparison of Guice and Spring, I recommend Eric Burke's initial impressions.
    The link posted by Paul Browne also quotes the above blog post: in essence,
    At the end of the day, I compared my modules — written in Java — to my Spring XML files. The modules are significantly smaller and easier to read.
  82. Re: From Spring to Guice[ Go to top ]

    The link posted by Paul Browne also quotes the above blog post: in essence,
    At the end of the day, I compared my modules — written in Java — to my Spring XML files. The modules are significantly smaller and easier to read.
    Don't forget the second part of the quote. :)
    Then I realized about 3/4 of the code in my modules was unnecessary, so I stripped it out. They were reduced to just a few lines of code each.
  83. interesting[ Go to top ]

    I like how in Guice don't require injection to follow strict java bean conventions. The use of type binding and marker annotations over string literals should help greatly for refactoring. Very interesting.
  84. Aw heck! Not uhgin![ Go to top ]

    Dependency injection with annotations - why compare this thing-uh-muh-jig? Compare it tuh Seam! And whut thuh heck is Google doin uh payin engineers tuh make IoC frameworks? The open-source offerings (Spring, Seam, etc...) provide more features than anyone rightly needs... Maybe Google will release a new open-source bubble sort next? Them waskals!
  85. Re: Aw heck! Not uhgin![ Go to top ]

    Maybe Google will release a new open-source bubble sort next?
    ...What we really need is an open-source Retroencabulator...
  86. annoying[ Go to top ]

    Does this Elmer Fudd crap annoy anyone else?
  87. Re: annoying[ Go to top ]

    Does this Elmer Fudd crap annoy anyone else?
    I think her (Elmira not Elmer) plan is working.
  88. Guice and Spring = complementary[ Go to top ]

    I can definitely see how these two frameworks are potentially complementary: I have myself written some code lately that basically adds Spring DI into objects created on the fly by annotations, to me this is the perfect mix. Some objects you might want to be created and managed directly through Spring and the traditional XML config, whereas some objects (such as Command objects created on invocation in my case) you might not be able to "bootstrap" in the same way, while at the same time you don't want to have Spring dependencies in them. In such a scenario DI through annotations is the perfect complement! / Wille Blog: Buzzword Bingo
  89. Looking at the examples, I'm just curious how Guice handles binding a DataSource to an implementation class (and how it passes various properties in to the DataSource). And how would you externalize different database connection profiles? (I'm guessing something like using Named bindings and putting the DataSource definitions into their own modules).
  90. Looking at the examples, I'm just curious how Guice handles binding a DataSource to an implementation class (and how it passes various properties in to the DataSource).
    You could write a custom provider, but if you already have a DataSource configured in JNDI, you might as well use JndiIntegration.
    And how would you externalize different database connection profiles? (I'm guessing something like using Named bindings and putting the DataSource definitions into their own modules).
    You could use custom annotations. For example, @Secure, @ReadOnly, etc.
  91. One of the main plus points of Spring is the fact that your domain model isn't dependent on the IoC framework in any way, that's the advantage of externalising the configuration into an XML file. Littering your code with Guice annotations may not be a good idea if your project out-grows Guice and you want to use a more fully-featured framework. Anyways, Spring's an active project with a large community and if annotation-driven IoC is what the community wants, I can't see it being too hard to implement a similar system for Spring.
  92. Yup, I think one of the big points made when Spring turned up on the scene was "programming with POJOs". It's amazing how much you can achieve with Spring without any API dependency on the framework. In fact, all the Spring docs encourage one to think very carefully before deciding to add API dependence on the framework. So, as well as requiring Java 5, these annotation-based approaches are not POJO frameworks. A class full of 3rd party annotations isn't a POJO any more -- it has dependencies on 3rd party framework code. I don't wish to bash Guice about this -- Guice seems pretty cool -- but it seems to be a big part of the Spring philosophy that they are perhaps missing. Regards John Hurst Wellington, New Zealand
  93. your code with Guice annotations may not be a good idea if your project out-grows Guice and you want to use a more fully-featured framework.

    Anyways, Spring's an active project with a large community and if annotation-driven IoC is what the community wants, I can't see it being too hard to implement a similar system for Spring.
    +1
  94. Do you have reference of Google projects using Google Guice ?
  95. My jripes (oops gripes) with guice[ Go to top ]

    This note really talks about some of my not so enthusiastic reactions to guice. That should not take away anything from my overall assessment that guice is indeed a new innovative DI engine and does provide some interesting and contrasting features to make it a welcome addition to the existing family of DI tools. I would probably want to revert back later with a more balanced view after putting it through its paces. @ImplementedBy There seems to be a fair degree of discussion on the merits of @ImplementedBy. I would argue guice in attempting to make DI more convenient (eg. better autowiring) really takes on the design constructs ie. interfaces and implementations, and creates some confusion on how these should be used. To me interfaces and implementations have often served as a clear mechanism of separation of the stable and volatile aspects of a design. If the interface API was as stable or as volatile as the implementation perhaps the designer wouldn't ever really create two .java files, and would simply implement a single Class with a public api representing its current interface. Clearly in this case a designer wouldn't have to worry about interface / implementation separation and the ImplementedBy tag wouldn't be required. Where the tag would get used is where there is a separate interface and implementation. This would happen under the following circumstances : (a) The designer intends to reflect different levels of stability (or volatility) in the two different constructs (b) The designer intends to have only one implementation but clearly leave an option to eventually have more implementations getting supported down the road. (c) The designer intends to use multiple implementations. The @ImplementedBy under each of this situations creates potential issues except for one specific scenario ie. The designer intends one specific implementation to be used in an overridingly large majority of situations and wants to allow an option where in a few rare situations, the implementation class could be overridden using some amount of externalisation of the configuration. Thus for situations not governed by the "dominant default implementation" scenario above using the annotation confuses the intent and stability of the two different constructs (interface and implementation). Thus it now really requires far more careful consideration each time whether one should indeed use the @ImplementedBy annotation. I would've actually been comfortable not having the annotation at all. However I think it wouldn't be difficult to have a coding convention in some teams such as "Thou shalt not use @ImplementedBy unless ...." or "Thou shalt not use goto unless ..." (That might seem like a flame bait - but I am using it in jest to just drive home the point). Annotating Bindings Refer to the section with the same name in the user guide for context The guide seems to suggest that if you need multiple bindings to the same type the same would get supported by using an additional annotation (eg. @Blue in the guide). This seems to be a mechanism of classifying the roles played by different implementations and then documenting the specific role name at the injection stage by specifying the annotation reflecting the role. This seems to "internalise" the role played by the service in the method into which it is getting injected. However that may not always be feasible. Clearly we would need mechanisms by which the annotation @Blue would need to get externalised into the the configure() method without having the document the same in the method with the @Inject annotation. If that is indeed feasible perhaps the user guide could be updated to reflect the same. Annotations Overdone ? When I start looking at the various capabilities I suspect somewhere the focus started to shift to how much could one push the capabilities using annotations as opposed to what do DI users really need. I could be wrong, but in that case the user guide needs to be updated to reflect the power of guice instead of the current state where I believe it is actually reflecting the power of annotations with guice just being a use case for the same. Readability Maybe because I am unaccustomed to it but the way the configure method needs to be implemented, the overall broad picture of the wiring just seems to be a lot less readable (and therefore less comprehensible) as compared to the other tools. - Dhananjay
  96. Thanks for the feedback, Dhananjay.
    @ImplementedBy
    I'm not the biggest proponent of @ImplementedBy myself, but here's the way I look at it:
    • Some users really wanted it.
    • You definitely don't have to use it. You can completely ignore it.
    • You can depend on a concrete class even more easily, so having @ImplementedBy does not make doing the wrong thing easier. It makes using interfaces a little easier, which is a good thing.
    • We are not Spring--we prefer to support one best way of doing things when possible, not every possible way. At the same time, we don't want to be too heavy handed, and we see this as a low risk feature.
    Annotating Bindings ... This seems to "internalise" the role played by the service in the method into which it is getting injected. However that may not always be feasible.
    Do you have an example of where an annotation won't work?
    Annotations Overdone? When I start looking at the various capabilities I suspect somewhere the focus started to shift to how much could one push the capabilities using annotations as opposed to what do DI users really need.
    I've been using Java 5 for over two years (and I used qdox, etc., long before that), so I have quite a bit of experience using annotations. I think Guice uses annotations appropriately, not to mention you can always resort to external alternatives when necessary.
    Readability ... Maybe because I am unaccustomed to it but the way the configure method needs to be implemented, the overall broad picture of the wiring just seems to be a lot less readable (and therefore less comprehensible) as compared to the other tools.
    By "other tools," do you mean Spring? I'll take a couple lines of Guice code and some @Inject annotations over a couple pages of Spring XML.
  97. Annotating Bindings ... This seems to "internalise" the role played by the service in the method into which it is getting injected. However that may not always be feasible.
    Do you have an example of where an annotation won't work?
    Sure. Couldn't think of a simple abstract scenario so stating one from the domain I work with. I might be interfacing with multiple Foreign Exchange Deal booking systems simultaneously. While each of them would effectively offer forex conversion, the cost and risk profiles are quite different. The approach as suggested would require the client objects (say these represent the transaction types) to document the "type of / role played by" the forex provider in its method definition (@Blue in the method with the @Inject tag). However such decisions cannot be made during the coding stage of the transaction type. These get deferred to deployment time based on the customer's risk appetite and the commercial considerations around that transaction type in the customer's context. Of course it is likely that theres some other way of doing the same in guice that I am not aware of.
    Annotations Overdone?
    I've been using Java 5 for over two years (and I used qdox, etc., long before that), so I have quite a bit of experience using annotations. I think Guice uses annotations appropriately, not to mention you can always resort to external alternatives when necessary.
    Reading the user guide simply forced me to deal with the underlying plumbing of the annotations far more than what I perhaps expected. Treat this as a feedback on the user guide.
    Readability ... Maybe because I am unaccustomed to it but the way the configure method needs to be implemented, the overall broad picture of the wiring just seems to be a lot less readable (and therefore less comprehensible) as compared to the other tools.
    By "other tools," do you mean Spring? I'll take a couple lines of Guice code and some @Inject annotations over a couple pages of Spring XML.
    Hmm, What if you are responsible for onsite production support and were not either involved in the development or initial deployment team. An analogy would be the electrical wiring and plumbing diagrams for a building. These are very essential for being able to quickly diagnose and fix issues on site in situations where the original electrical and plumbing teams are just far removed and lets say located in the Head Office. Legible wiring diagrams for non trivial DI implementations are an important requirement, and if the tool itself doesn't make it easy, then additional effort would need to be spent to create and regulary maintain the same leading to duplication of such information and possible errors in the same. - Dhananjay
  98. Do you have an example of where an annotation won't work?
    Sure. Couldn't think of a simple abstract scenario so stating one from the domain I work with. I might be interfacing with multiple Foreign Exchange Deal booking systems simultaneously. While each of them would effectively offer forex conversion, the cost and risk profiles are quite different. The approach as suggested would require the client objects (say these represent the transaction types) to document the "type of / role played by" the forex provider in its method definition (@Blue in the method with the @Inject tag). However such decisions cannot be made during the coding stage of the transaction type. These get deferred to deployment time based on the customer's risk appetite and the commercial considerations around that transaction type in the customer's context. Of course it is likely that theres some other way of doing the same in guice that I am not aware of.
    I would probably write a custom provider which returns the appropriate booking system for the current customer context.
    Reading the user guide simply forced me to deal with the underlying plumbing of the annotations far more than what I perhaps expected. Treat this as a feedback on the user guide.
    Point taken. We could use a separate reference, or at the very least we'll better organize the user's guide.
    Hmm, What if you are responsible for onsite production support and were not either involved in the development or initial deployment team. An analogy would be the electrical wiring and plumbing diagrams for a building. These are very essential for being able to quickly diagnose and fix issues on site in situations where the original electrical and plumbing teams are just far removed and lets say located in the Head Office. Legible wiring diagrams for non trivial DI implementations are an important requirement, and if the tool itself doesn't make it easy, then additional effort would need to be spent to create and regulary maintain the same leading to duplication of such information and possible errors in the same.
    You should write documentation for your production team. You can use the time you would have otherwise spent writing and maintaining Spring XML. Spring XML does not replace documentation. The production engineers will also be better able to fix things if you provide them we a small set of things they can safely tweak, i.e. in a properties file or JMX interface.
  99. Re: My jripes (oops gripes) with guice[ Go to top ]

    Do you have an example of where an annotation won't work?

    Sure. Couldn't think of a simple abstract scenario so stating one from the domain I work with. I might be interfacing with multiple Foreign Exchange Deal booking systems simultaneously. While each of them would effectively offer forex conversion, the cost and risk profiles are quite different. The approach as suggested would require the client objects (say these represent the transaction types) to document the "type of / role played by" the forex provider in its method definition (@Blue in the method with the @Inject tag). However such decisions cannot be made during the coding stage of the transaction type. These get deferred to deployment time based on the customer's risk appetite and the commercial considerations around that transaction type in the customer's context. Of course it is likely that theres some other way of doing the same in guice that I am not aware of.


    I would probably write a custom provider which returns the appropriate booking system for the current customer context.

    Reading the user guide simply forced me to deal with the underlying plumbing of the annotations far more than what I perhaps expected. Treat this as a feedback on the user guide.


    Point taken. We could use a separate reference, or at the very least we'll better organize the user's guide.

    Hmm, What if you are responsible for onsite production support and were not either involved in the development or initial deployment team. An analogy would be the electrical wiring and plumbing diagrams for a building. These are very essential for being able to quickly diagnose and fix issues on site in situations where the original electrical and plumbing teams are just far removed and lets say located in the Head Office. Legible wiring diagrams for non trivial DI implementations are an important requirement, and if the tool itself doesn't make it easy, then additional effort would need to be spent to create and regulary maintain the same leading to duplication of such information and possible errors in the same.


    You should write documentation for your production team. You can use the time you would have otherwise spent writing and maintaining Spring XML. Spring XML does not replace documentation. The production engineers will also be better able to fix things if you provide them we a small set of things they can safely tweak, i.e. in a properties file or JMX interface.
    You are irresponsibly misrepresenting the complexity of Spring XML. Have you written a Spring-based app? It's dead simple. I know of no Spring developers who complain about writing or maintaining Spring XML. Also, lets make sure we're comparing apples to apples. Some Spring XML might appear complex only because it's doing much more than DI, e.g., transaction management, aspects, RMI exporting. Spring XML doing pure DI is just a simple as Guice's bind code. With autowiring it's even more simple: just a list beans. Really, though, both methods of DI configuration are simple enough and not worth quibbling over. The crux, however, is that a glue framework should be unknown to the code being glued: Spring respects this; Guice does not. Who wants a bunch of Guice turds peppered throughout their code? Try explaining what all of those @Inject, @ImplementedBy and "@Blue" tags are to new developers after your project migrates to another DI framework. The classes in my Spring apps are POJOs, where Plain means plain. Lose the annotations and I might get on board. The performance improvement over Spring sounds good (even if it is just on startup). Also, considering Guice doesn't "compete directly" (http://code.google.com/p/google-guice/wiki/SpringComparison) with Spring, why do you endlessly point out Guice's superiority to Spring? If you're going after Spring, great; just be honest about it. BTW, I'm a big Goggle fan: Gmail, GWT, Calendar.
  100. Oops. Goggle -> Google. Damn...no edit.
  101. Re: My jripes (oops gripes) with guice[ Go to top ]

    You are irresponsibly misrepresenting the complexity of Spring XML. Have you written a Spring-based app? It's dead simple. I know of no Spring developers who complain about writing or maintaining Spring XML.
    Those developers probably don't know anything different. I don't think I've ever referred to Spring XML as complex--just rote and repetitive. It's code I'd just assume not write.
    Also, lets make sure we're comparing apples to apples. Some Spring XML might appear complex only because it's doing much more than DI, e.g., transaction management, aspects, RMI exporting. Spring XML doing pure DI is just a simple as Guice's bind code.
    Comparing Spring XML to Guice binding code is not apples to apples.
    Really, though, both methods of DI configuration are simple enough and not worth quibbling over.
    OK... ;)
    The crux, however, is that a glue framework should be unknown to the code being glued: Spring respects this; Guice does not. Who wants a bunch of Guice turds peppered throughout their code? Try explaining what all of those @Inject, @ImplementedBy and "@Blue" tags are to new developers after your project migrates to another DI framework. The classes in my Spring apps are POJOs, where Plain means plain.

    Lose the annotations and I might get on board.
    We follow a more practical philosophy which has been discussed in depth on our mailing list.
    The performance improvement over Spring sounds good (even if it is just on startup).
    Actually, it's runtime performance. I haven't tested startup performance.
    Also, considering Guice doesn't "compete directly" (http://code.google.com/p/google-guice/wiki/SpringComparison) with Spring, why do you endlessly point out Guice's superiority to Spring? If you're going after Spring, great; just be honest about it.
    It doesn't compete directly. You said yourself Spring does much more than DI. Guice does not.
  102. Clearly in this case a designer wouldn't have to worry about interface / implementation separation and the ImplementedBy tag wouldn't be required.

    Where the tag would get used is where there is a separate interface and implementation. This would happen under the following circumstances : [snip]
    You are forgetting about the whole area of AOP. With AOP interfaces get a slightly different purpose, as an "object" does not implement one interface but rather in the range of 10-15 or more, depending on the situation (that's our typical case anyway). It's a bit too large of a discussion to take here and now, but I thought I'd just mention it anyway as another important usecase where interfaces are necessary.
  103. Rickard, Quoting the AOP usecase as the basis of the generalization you made on Interfaces and their implementations earlier here on this thread looks weak to me. After all how many enterprise developers use AOP? Again, if that argument you made is solely based on your AOP experience then it doesn't hold water to me. Regards, Jan
  104. Rickard,

    Quoting the AOP usecase as the basis of the generalization you made on Interfaces and their implementations earlier here on this thread looks weak to me. After all how many enterprise developers use AOP? Again, if that argument you made is solely based on your AOP experience then it doesn't hold water to me.

    Regards,
    Jan
    You are, again, assuming black and white situations ("solely based on"), and you are again assuming that this single case is the reason I said what I did (projection). Please, just stop it.
  105. Rickard,

    Quoting the AOP usecase as the basis of the generalization you made on Interfaces and their implementations earlier here on this thread looks weak to me. After all how many enterprise developers use AOP? Again, if that argument you made is solely based on your AOP experience then it doesn't hold water to me.

    Regards,
    Jan

    You are, again, assuming black and white situations ("solely based on"), and you are again assuming that this single case is the reason I said what I did (projection). Please, just stop it.
    Rickard, Read my post again, I said
    if that argument you made is solely based on your AOP experience ...
    And I stress the conditional if, you get it? It's just like the "if" in the Java language, which I know for sure you understand it's semantics, right? :-). Regards, Jan
  106. And I stress the conditional if, you get it? It's just like the "if" in the Java language, which I know for sure you understand it's semantics, right? :-).

    Regards,
    Jan
    Alright, if you want to be picky you should have noted that I said that AOP is "another" usecase for interfaces, as in "an other", not "only".
  107. You are forgetting about the whole area of AOP. With AOP interfaces get a slightly different purpose, as an "object" does not implement one interface but rather in the range of 10-15 or more, depending on the situation (that's our typical case anyway).

    It's a bit too large of a discussion to take here and now, but I thought I'd just mention it anyway as another important usecase where interfaces are necessary.
    Rickard, Thanks for the additional thought. Yes, I did not have AOP in mind, and yes, it is indeed an important use case. I can certainly imagine a lot of the interfaces could perhaps have only one implementation leading to @ImplementedBy being a helpful construct. In your opinion would the nature of usage of the constructs in such a situation conform to what one would associate with the term "Dependency Injection" or is there some very different kind of Injection happening here (perhaps functionality / common capability injection) ? Dhananjay
  108. Thanks for the additional thought. Yes, I did not have AOP in mind, and yes, it is indeed an important use case. I can certainly imagine a lot of the interfaces could perhaps have only one implementation leading to @ImplementedBy being a helpful construct.

    In your opinion would the nature of usage of the constructs in such a situation conform to what one would associate with the term "Dependency Injection" or is there some very different kind of Injection happening here (perhaps functionality / common capability injection) ?

    Dhananjay
    Very good point. The motivation is definitely similar, that is, to put your assumptions about the system in as few places as possible. I wouldn't call it Dependency Injection to avoid confusion, but the mindset is the same.
  109. For developers who have become accustomed to using Spring's transaction management and support classes such as Hibernate Template (and being given the correct Session for the open transaction), what is the Guice way? Coarse grained transactions in a filter and a static HibernateUtils?
  110. A better way of asking that might be: For developers who use a larger part of Spring than just IoC is there any assistance given by Guice to help them move away?
  111. For developers who have become accustomed to using Spring's transaction management and support classes such as Hibernate Template (and being given the correct Session for the open transaction), what is the Guice way? Coarse grained transactions in a filter and a static HibernateUtils?
    Guice supports Spring's transaction interceptor (and any other AOP Alliance interceptor). If Spring's other components don't actually depend on the DI container, there's no reason you shouldn't be able to use them with Guice, too. If all of that fails, check out SpringIntegration.