How do you keep an overview over which objects get injected where? I have a rather small project where i use guice, not so much because i really need it (given the project is still small), but rather because i want to get to know it a little better.
I am already starting to loose the overview with only ~10 classes; are there tools that analyze the code to show something like a dependency graph?
That would make it easier to see quickly where i forgot something or where i need singleton scoped injection. Also with guice a lot of things happen implicitly, being able to see these things explicitly would help debugging in the future.
I have a couple of principles which help to manage dependencies using Guice.
Keep all bindings inside modules only. Do not use just-in-time bindings stuff. I mean, do not use #Singleton or #ImplementedBy or #ProvidedBy, i.e. all that is described here. Try also always call binder.requireExplicitBindings() at the top of your modules - it will force you to always bind your dependencies explicitly. When you keep all dependencies to the modules, you can easily find which interface fulfilled by which implementation. This simplifies navigation around bindings a lot.
Try to keep your modules as small as possible, and then combine them when creating an injector (directly via createInjector() call or using a central module which does nothing but install()s other modules). Each module should be responsible for its own part of the application and should be named accordingly. Also your modules should not contain complex initialization and dynamic binding code. This way you will be able to find a module which is responsible for some part of your application quite easily.
These principles are really simple but they make dependency management very easy.
Also, you can visualize dependency graph using special Guice extension. It has it bugs though, and it has been a while since I have used it, so I can't give you exact links on how to avoid these bugs, but googling for it won't take long.
Related
I have been reading the book Spring in Action for a few weeks now to learn about the spring framework. I have about 2 years of programming experience mostly in java with some distractions here and there in Ruby and Python.
After reading the first few chapters, I didn't quite get what the big deal is about dependency injection in spring. I was expecting a AHAAA moment but didn't quite experience that yet. I'm sure I'm missing something important.
Why would I want to wire my beans in xml rather than instantiating them the good old way with the = new myclass();
I understand I can wire beans in the xml via constructor args and properties as well as configure datasources in spring so that I can hide away connection details in an xml file. But why? There is more to this especially when it comes to good software design. Can some one explain the big deal?
Three Words: INVERSION OF CONTROL
In a nutshell:
As soon as you instantaniate "the good old way" you create tight coupling, e.g.: your controller depends on a specific template engine, your entities on a concrete database layer, etc. And that's something you want to prevent and where the dependency injection container (DIC) comes in very handy. It manages your services and you don't really have to care anymore about specific implementations as long as those implement the same interface.
Imagine a simple storage layer class called InMemoryLayer that gets instantiated by you when need it. Now you want to switch it for an awesome new open-source github solution called SuperSecretRemoteCloudLayer. Normally you would now hit "Search and Replace" in your IDE of choice and replace all occurrences of InMemoryLayer with the SuperSecretRemoteCloudLayer. But that's not really handy and quite errorprone, why would you want to do all that hard work by hand? The DIC can do that for you and all you need to take care of, is that both *Layer implement the same interface (so your application won't break).
Spring's big deal is more about dependency injection, not XML-based configuration. As others have noted, Spring has been moving away from XML-based configuration. But DI is core to Spring.
The a-ha is that DI offers a different model for linking components together. Instead of components creating each other directly (and thus being tightly coupled), the components stop doing that, and you inject the linkages from a central location. It turns out that this helps with testing and transaction management in particular.
You don't truly appreciate Spring until you've had to do things the hard way. The hard way being maintaining multiple large projects without a coherent framework. If you have 4 big enterprise wide applications that all have their own way of starting themselves, and managing resources, you're in for a headache. If you know that each application uses spring, then just look for the application context xml! This also makes it incredibly easy to setup a new context for different environments, and test cases, all without mucking up your code base.
So I'm writing a bunch of components (that will be packaged as JARs), and they are all using Guice for DI. These components are just reusable, "commons"-type JARs that will be used by other downstream projects.
My understanding with Guice is that you implement a concrete Module and use that to bind objects together and, in effect, configure all of your DI. It is also my understanding that you should then have a single "bootstrapping" phase where the Guice injector is created, and then all dependencies the module is configured with are then fetched from that injector with injector.getInstance(SomeClass.class).
That would work great in standalone application, that had some entry point, where you could invoke an init()-style method to then bootstrap Guice with, but in a headless JAR that has no entry point, I'm struggling with trying to determine when/where/how to bootstrap Guice.
These will be JARs living on the classpath and, at any point in time, an external entity could invoke and class and any method inside of them. I thought about using up a "lazy initialization" set up, where a method checks to see if its dependencies have been configured yet, and, if so, kicks off a bootstrap method.
But that's a really terrible solution! Partly, because that would require every class to have its own Module (which is ridiculous), and it would also pollute my entire codebase with DI-related code.
I'm clearly missing some Guice fundamentals here, otherwise I don't see how Guice could be used in anything other than an app where execution from start to finished is known and controlled. Any code samples are a huge plus! Thanks in advance.
If other code wants to configure your classes without using Guice, it should be able to. However, you should provide a Guice module which binds everything in a reasonable way so that other code (perhaps other modules) can install your module, and then inject the dependencies into their own classes.
Of course, you don't need to expose a module yourself at all - you can leave it up to others to perform all the binding. However, you may wish to provide a module to avoid exposing your implementation details - you can expose a public interface and a public module, but then keep the implementation package-private. The module can bind the interface to the implementation without the caller knowing anything about it.
You may also want to investigate private modules, so that you can bind dependencies that your code needs, without exposing them more widely.
Something, somewhere is going to have to create an injector - but if your code is just "library" code, then it almost certainly shouldn't be you. You shouldn't be performing the injection yourself - you should just be making your code amenable to injection.
I'm comfortable programming in Java, but am fairly new to Spring. I've been reading about dependency-injection/inversion of control (and using it with Spring for the past few months), but I can't figure out the need for a separate language (xml/spring) to accomplish it.
What is wrong with creating a singleton in Java called DependencyHandler, and keeping everything in the same language? What are the advantages I get by using xml/Spring?
Dependency Injection does not require a separate language.
Spring is a framework for Java that historically required configuration in xml. Now you can configure it using xml, or java annotations.
Google's Guice is a simple dependency injection framework that has all configuration in Java.
There can be legitimate reasons why a custom language (in xml) can be better than Java for a specific purpose. For DI though, the reasons are stretchy, and in fact, not the real reasons.
From countless testimonies from happy Spring users, the overwhelming reason is that they somehow think xml is not code. They are so tired of writing boilerplate Java code, they are happy to switch to boilerplate xml. And that makes them happy.
Human beings are not rational when it comes to economic matters. We have elaborate systems that transfer resources in circles, finding comfort and security in such pointless waste of efforts.
But I guess happiness is the most important thing, however retarded it could be.
You can make dependency injection frameworks that use Java syntax, too. Just look at Google Guice, for example.
I'll answer the "benefits" part for XML specifically, although there aren't many.
Having configuration completely separate from code removes all framework artifacts from the source, which can be beneficial.
It's easier (not ridiculously so, but enough to be noteworthy) to create toolchains that affect configuration files: property loading/replacement, config-aware GUI config editors, documentation generation, etc.
Centralized configuration; instead of config being strewn around the codebase, it's in a group of files (or single file). This isn't an XML-only vitrue, it depends on how things are configured.
I think some types of configuration lend themselves to external configuration more than others. I choose based on what seems appropriate given the reqs, what the framework allows, and how the framework handles config aspects.
Spring is just an easy way to manage dependency injection in large projects.
But you can inject dependencies by using a static factory method on your class:
public class Foo
{
public Foo static mkFoo(/* dependencies */)
{
// assign dependencies to members
}
// ordinary class stuff
}
Then you just do Foo.mkFoo(/*dependencies*/) whenever you want a Foo. No spring required.
What is wrong with creating a singleton in Java called DependencyHandler, and keeping everything in the same language?
Handling all your dependencies in a single class is going to get messy quickly, and will result in coupling with all of your other classes. But that isn't a reason to not handle DI in plain java.
We basically need to be able to adjust behaviour at start-up time, by providing desired classes to be produced by various factories inside our application (to avoid the hard binding of the "new" operator).
I am aware that this is provided by several large frameworks, but I was looking for something easily used by a stand-alone Java application without being gigantic.
Any suggestions?
Edit: It is my experience that frameworks tend to grow big as part of maturing (and complex too). I need this to be retrofittable to a legacy application as part of major refactoring (technical debt), so simplicity is essential of the used libraries. I do not mind having to do a bit of coding in our application, but it must be very visible what is going on. AOP has a tendency for moving stuff out of the way, and that may make the application harder to maintain.
Edit: We have now reached the point where we actually need to make a decision. The application will probably live for decades so we need to make a reversible decision with a framework that will be maintained for hopefully as long. I really like the static type check available with Guice, but not that the annotations bind explicitly to Guice instead of being external like in Spring. I also like that code appears to be more concise when using Guice as opposed to Spring. We need something that is robust and helpful. We do not need more than just DI at the moment. Is there a use case that definitive says go for one of these?
Edit 2011-07-27: The final decision was to use the JSR-330 API in code, and choose on a per-project basis if to use Spring, Guice or Weld. For stand-alone applications Guice has worked well so far as the JSR-330 implementation.
You can always use Spring Framework 2.5. It is a big one, but if you planning to use only DI you can use spring-core and spring-beans modules, which are pretty small (ca. 500KB and 300KB).
There is also Google Guice 2.0 which comes with a package with only basic stuff (no AOP) and it's 430KB.
Have you looked at the Google Guice framework? It's pretty lightweight and annotation-based, avoiding XML configuration files
There's also Pico- and Nano-container (from codehaus) which are quite lightweight although the last time I looked (admittedly a few years ago) the documentation was lacking.
I must say that I agree with others about what I assume is your presumption that Spring is massive and confusing. It's really a very simple IoC container and to be recommended.
There are a couple I know of you might find useful:
PicoContainer
Plexus (used in Maven)
I've found Plexus very useful in standalone apps as it has optional utility components for CLI interaction.
By "gigantic" I'm going to assume you're referring to Spring, but that's unfair, since you can cherry-pick the bits of Spring you want to use. If all you need is the IoC container, just use the appropriate JAR files and the appropriate bit of the API, and ignore the rest of it.
Most answers so far seem to be concerned with the size of the jar files to be added.
However I think the more important question is the impact on the project: How many lines of code must be added/changed in order to use the framework?
Even the "big" spring framework is actually very easy to use:
You basically need:
a xml file that describes your factories.
one line of code to initialize the container by loading the xml file
The nice thing is that spring is non-intrusive. So you do not have to implement specific interfaces or add any specific annotations or imports to your classes.
At best the single spot where you actually initialize the Spring container is the only
place in your application that has an actual dependency to spring classes.
I would strongly suggest to take a look at Spring ME. Although originally meant to be a way to use Spring on Java ME applications, it also works fine for standalone applications.
True, it doesn't give you all of the bells and whistles that Spring (Full) has to offer, but then again, Full Spring is much much more than a simple dependency injection framework.
On the plus side: it's based on a (compliant) subset of Spring's configuration files, and the footprint of the runtime is 0%. In fact, there isn't any. Spring ME will take your application context, and turn it into a class that has no dependencies on classes other than your own.
What's wrong with Spring?
These days it's packaged pretty well so you wouldn't need to take the whole kit and caboodle.
As an aside, I'm not a fan of the annotation based injection frameworks. This is because the annotations are bound to the class rather than the instance, the later being a pre-requisite, imho, for DI. This means every instance of a given class gets the same object(s) injected, which seems to defeat the point.
Also consider that DI doesn't even need a framework, what's wrong with your main method wiring together the application?
If you want something maximally simple and appropriate, then write some code that does what you want done. Presumably this involves wiring together factories based partly on fixed logic, and partly on run-time settings.
This has the advantage that the set of possible run-time configurations is known, and so documentable and testable.
It has the disadvantage that an deploying an unanticipated logic change inherently takes an extra second or so of compile time, and (more significantly) can't be sneaked into production without full testing by disguising it as 'just a configuration change'.
About a year ago I asked myself a question very like this. So I spend a few hours reading the Spring and Guice documentation. After about an hour with Spring I was left feeling that I could get a basic web app going, but had no idea how to use it in a stand alone application. After an hour with the Guice document everything had clicked and I could see just how I to do what I wanted to get done.
Now on to recommending Guice? Well no. What does your team already know? If someone already knows say Spring leaver that knowledge and have them spread it about. Like wise with Guice or Pico.
If you want something really light weight you might want to have a look at fuse it's fairly extendable so might be what you're looking for.
cheers
N
I often read about dependency injection and I did research on google and I understand in theory what it can do and how it works, but I'd like to see an actual code base using it (Java/guice would be preferred).
Can anyone point me to an open source project, where I can see, how it's really used? I think browsing the code and seeing the whole setup shows me more than the ususal snippets in the introduction articles you find around the web. Thanks in advance!
The Wave Protocol Server is my favourite example app.
I struggled a bit with this exact issue. It's so abstract and simple I was always worried I was "doing it wrong".
I've had been using it in the main project which has dependencies on other projects because the Guice module which sets the bindings was part of the main project.
I finally realized the libraries should be supplying the Modules themselves. At that point you can depend only on an instance of a Module (not a specific one), and the interfaces that are bound by it.
Taking it one step better, you can use the new ServiceLoader mechanism in Java 6 to automatically locate and install all Guice modules available on the classpath. Then you can swap in dependencies just by changing class path (db-real.jar vs. db-mock.jar).
I understand you're in Java-land, but in the .NET space the are several open-source apps written using an inversion of control container. Check out CodeCampServer, in which the UI module doesn't have a reference to the dependency resolution module. There is an HttpModule that does the work. (an HttpModule is just a external library you can plug in that handles events in ASP.NET, in CodeCampServer the UI project loads this DependencyRegistrarModule at run time, without any compile time reference to it.)
I think dependency injection has a way of disappearing from view if used properly, it will be just a way of initializing/wiring your application -- if it looks more fancy than that you are probably looking at extra features of the framework at hand, and not at the bare-bones dependency injection.
Edit: I'd recommend actually starting to use it instead of trying to find examples, and then come back and post questions here if you can't get stuff to work like you'd think it should :-)