Guice is a light-weight dependency mechanism for those who don’t the big guns in Spring. If Guice makes your code hard to understand, and if you are running Groovy, roll your own. The dependency support class is as simple as:

class Dependency {
    static contexts = [:]
    static globals = [:]
    static injection(context) {
        def dependents = contexts.containsKey(context) ? contexts[context] : globals
        return dependents ? { dependents.containsKey(it) ? dependents[it] : it } : { it }
    }

For any class with dependencies you make a static closure by calling injection and replace all new statements:

class B {}
class A {
    static dependent = Dependency.injection(A)
    def b = dependent(B).newInstance()

If this is all you do then your code will run exactly as before.

a = new A()
assert a.b.class == B 

But now it is possible to over-ride any dependency globally…

Dependency.globals[B] = String
a = new A()
assert a.b.class == String 

or specific to the a class:

class C {}
Dependency.contexts[A] = [(B) : C]  // or;
a = new A()
assert a.b.class == C
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s