A CDI Primer: Part 2

In the previous post we covered Contexts and Contextuals and the relationship between them.  A Contextual, briefly, is the CDI representation of a producer (a CDI-independent concept within the dependency injection mindset we covered in part 0) focused solely on the mechanics of production, with no responsibility for caching or storage or any other kind of lifecycle management.  A Context is CDI’s façade of sorts for Contextuals that has no responsibility for making objects of a given kind—it uses Contextuals for that—but all kinds of responsibility for managing the lifecycles of those manufactured or acquired objects.

We also learned that contextual instances are effectively the return values from the Context#get(Contextual, CreationalContext) method invoked on a given Context (and by extension the return values of implementations of the Contextual#create(CreationalContext) method.)  If your class has an @Inject-annotated “slot” in it, and it gets “filled” by CDI, then you just took delivery of a contextual instance from a Context, created by a Contextual.

In this post we’ll start looking at the actual mechanics that CDI uses to match contextual instances to consumer “slots”, and the beginnings of how those pieces of the machinery are found in the first place.

A Digression on Java Generics

And now, for everyone’s favorite subject: Java generics.

First, some housekeeping.  I’m going to run right into the utterly awful WordPress editor which is schizophrenic about angle brackets.  Java generics feature a lot of angle brackets.  They disappear in WordPress.  (Using ampersand-lt-semicolon and similar SGML-entity-based “solutions” doesn’t work, because the helpful editor will expand it in place, then save the result, neutering the attempt to use them in the first place.)  So I’ll use curly braces instead.  Just squint a lot and you might even be able to see them as angle brackets.

Suppose I have a field whose type is List{Number} and you have a List{Integer}.  Can I take your List{Integer} and put it into my List{Number}-typed field?  No, I cannot.  You can learn more about this from the Java Tutorial if you need to.  This is a case of trying to figure out assignability of parameterized types (like List{Number} and Class{T} and so on).  In order to do wiring properly, you—or the magic system that is going to do the wiring for you, like CDI—have to get this right.

Now, if I have a field whose type is List{? extends Number} and you have a List{Integer}, that will “go into” my field just fine.  So the person or machine doing wiring has to take wildcards into account as well.

Typesafe Resolution

This process of accounting for all sorts of different types—simple-typed slots like fields with types like Number or complicated slots with parameterized types like List{Number}—and matching those slots to compatible types, such as the return types of all producers in the system, is known as typesafe resolution.  “Typesafe” here is meant to emphasize the fact that—unlike some other dependency injection frameworks such as the machinery that was in Java EE at the time—CDI matches types, not names: your @Inject-annotated field’s type is matched to a producer’s type.  (Earlier dependency injection frameworks used name matches, which are more brittle.)  “Resolution” refers to the fact that a consumer’s slot has been matched, or resolved, to a particular production type—and thereby to a particular dependency.

Let’s say that CDI can somehow find all the slots in my classes that need contextual instances.  And it can find producers that make all different sorts of contextual instances of all different sorts of types.  If there is exactly one producer in that big pile of producers (of any kind—constructor, method, field…) whose production type is assignable to a given slot, then we have a match: we say that typesafe resolution has completed successfully, and we know that that wiring can be set up automatically.  If I have a slot that asks for a Gorp, and there is exactly one producer that returns a Gorp (or a Gorp subclass), then as we saw back in part 1 we can just “see” that that producer should be called to fill that slot.  CDI can therefore also “see” that this is the case, so is able to make it work.

Unsatisfied Dependencies

What happens when there is no producer whose production type is assignable to my @Inject-annotated field’s type?  We say in this case that typesafe resolution failed because we have an unsatisfied dependency.  I asked for a Gorp , but there wasn’t any Gorp producer that could respond.  The wiring cannot be completed automatically.

Ambiguous Dependencies

What happens when there are lots of producers whose production types are all assignable to my @Inject-annotated field’s type?  We say in this case that typesafe resolution failed because it was ambiguous.  The wiring cannot be completed automatically.  Without further information, CDI can’t make a call on which producer to select to produce an object to go in the right slot.

Finding the Right Context

Let’s say that I have a class named Backpack with a field whose type is Gorp, and there is exactly one producer in the world (represented as always in CDI by a Contextual under the covers) in some handwavy unspecified fashion that returns Gorp, and so CDI in the abstract is able to at least conceptually connect the two—i.e. typesafe resolution succeeds.

While talking about typesafe resolution, we’ve been talking about consumers and producers (Contextuals), but we’ve quietly tabled any mention of Contexts.  Let’s bring them back into the conversation.

Recall that a Context is responsible for fronting a producer (a Contextual), and for deciding when and for how long to cache its results, and that it is a Context implementation that ultimately supplies dependencies, calling upon the services of a Contextual implementation when required.

Graphically, our little case might look like this, using UML notation:

ProducerConsumerContextClassDiagram

Here, I’ve colored the CDI internal interfaces gray, our application classes (Backpack and Gorp) cyan, and then have highlighted in pink and red respectively a hypothetical Context implementation and a hypothetical Contextual implementation.  I’ve also used «stereotypes» to help with keeping the terminology straight.  Once again I’m going to have to use curly braces in my text below instead of angle brackets thanks to the WordPress editor’s many flaws.

You can see that in general a Context uses a variety of Contextual implementations to serve dependencies.

You can also see that in this case there is a Some Context Implementation? that fronts a Some Contextual{Gorp} Implementation? that is the ultimate producer of Gorp instances.

The Context implementation is going to have rules in it about when to return the same Gorp instance and when to create a new one.

The Contextual{Gorp} implementation is the producer and is going to be concerned with how to make a Gorp instance.

These classes are components in the same way that our Backpack and Gorp classes are components.  There can be many Context implementations in the system, and there can be many Contextual implementations in the system, all supplying different types, and all blissfully unaware of who might be asking for those types.  Further, a Contextual doesn’t know what Contexts might be using it, and a Context doesn’t know what Contextuals there are in the world.

So how does CDI figure out which Context implementation to pick to serve up Backpack‘s Gorp dependency?  And, even if it somehow magically does that, how does it then also figure out that the Context in question should use a particular Contextual to “back” it?

You can see, I hope, that there must be some kind of a mechanism available to let CDI know at the very least how a Contextual implementation might be linked with a Context implementation.  That hinting mechanism is a CDI construct called a scope.

Scopes

If a Context implementation is where contextual instances used by consumers come from, then a scope is a construct that indicates to CDI that this Contextual over here “goes with” that Context over there.

That is, in a very abstract sense—and we’ll get concrete soon enough—you mark a Contextual in some way that lets CDI see from that marking that the Contextual “belongs” to a certain Context implementation.

So if there is a Context in the world in some kind of handwavy unspecified fashion, and it can somehow identify itself to CDI as a producer of singletons (let’s say), and you have a Contextual implementation whose returned objects you want to be singletons, then you brand your Contextual in a particular way that identifies it as belonging to the singleton Context implementation.

The shape that this mechanism actually takes in CDI is very simple.  A scope is a particular kind of annotation class.  (Scopes happen to be any annotation classes that are themselves annotated with either javax.inject.Scope or javax.enterprise.context.NormalScope, but for this discussion we don’t really care about that for the moment.)

Let’s keep rolling with our singleton Gorp case.

When we introduced Contexts, we focused exclusively on the get methods.  But there is another interesting method on Context.  It is getScope.

That method returns an annotation class that basically ends up labelling the Context implementation.  The Context can now be matched or looked up under this annotation class label.

So, for example, CDI happens to ship with a built-in Context whose getScope method returns javax.inject.Singleton.class.

On the “other side”, it turns out you can mark certain Contextual implementations with that same annotation.  We’ll see exactly what shape this takes a little later; for now just know you can do it.

So if our Contextual{Gorp} implementation is somehow annotated with javax.inject.Singleton, then CDI now has what it needs: it can find the Context implementation indexed under Singleton.class, and “link” it with the Contextual{Gorp} implementation annotated with that annotation.

Then, assuming that typesafe resolution has succeeded, as it would in our trivial example, CDI now knows that it can complete the wiring automatically: our Backpack class will make an implicit request of CDI’s built-in-Context-implementation-associated-with-Singleton.class, and that Context implementation will use the Contextual{Gorp} that was annotated in some handwavy way with @Singleton.  The circuit is complete.

Our Backpack can now take delivery of a Gorp and anyone else who asks for a Gorp will get back the very same Gorp instance, not a new one.

Enough Handwaving

We’ve done a lot of handwaving to get to this point.

  • We’ve handwaved over what Contextual implementations can look like.
  • We’ve handwaved over how CDI figures out what producers and consumers exist in its world.
  • We’ve handwaved over how CDI figures out what Contexts exist in its world.
  • We’ve handwaved over exactly when CDI performs all this discovery.

We’ve probably also handwaved over a lot of other stuff.

At least some of the handwaving will start to end in the next post!

A CDI Primer: Part 1

In the previous article, we dabbled briefly in looking at the surface of the iceberg that is the CDI machine for making @Inject work as a way of answering some basic questions about what, exactly, CDI does and why you might want to use it.

We also, much more importantly, looked into the dependency injection mindset.  We talked about abstract notions of producers and consumers and wiring them together.  We introduced the idea that if you look through the right lenses, fields, methods and constructors can all be producers housed in particular producer classes.  And finally we pointed out that producers can be consumers and vice versa.

Now let’s talk about lifecycles.

Object Lifecycles and “Producer Proxies”

When a producer of any kind “wants” to make or supply or acquire an object, two decisions have to be made:

  1. how to make or supply or acquire the object
  2. when to make or supply or acquire the object regardless of how that happens

Some producers, as we saw in the previous article, are, as often found in the trenches of enterprise Java development, what I’ll call singleton suppliers.  They acquire the (mostly!) One True Instance™ of the object in question somehow, sometimes creating it once if necessary, sometimes by interrogating some ancient snarling hairball of a legacy system, and then from that time forward in the whole life of the application, that’s the object you get if you ask them to supply it to you.

Other producers, like constructors, create a new object each time one is to be produced because they can’t do anything else, or they’re kind of uninterested in the ways that they might be called, so they shrug and say, hey, if you want a new object, call me; otherwise, don’t; I don’t store or cache nothin’.

What’s interesting about producers of any kind, in isolation, without any other technologies such as CDI or its subsystems in play, is: producers in isolation combine how an object is produced with when it is produced.

For example, what I’ll call singleton suppliers—those all-too-common “enterprisey” methods that somehow acquire a Singleton From Elsewhere™ and then return it when asked—are combining the mechanics of how the singleton is produced (maybe it’s looked up from some other system) with when it is produced (maybe this system lookup only happens once and then the result is stored as a static singleton).

Or constructors: if you acquire an object from a constructor—a kind of producer, remember—then no matter what you do and no matter what it does you’ll get a new instance of the produced object each time because that’s what constructors do.

What would be nice is to let producers do what they do—acquire or make things when called for—and have there be some other subsystem that controls when a produced object is handed to a consumer.  Something that can go “back to the well”—the producer “well”—when needed, but not when not needed, and is in full control of when that happens, but does not itself know how the manufactured items it is storing or caching are made.  Something that is kind of like a proxy for producers: something that can stand in front of them and hand out their results when appropriate, regardless of how they were made or from what system they were acquired, according to its own notions of lifecycle.

ProducerConsumerUseCase

In such a situation a producer can focus on how to acquire an object but not on how to cache it; a producer proxy can focus on when to cache an object, if at all, and when to clear the cache; a consumer, in grand dependency injection mindset fashion, can remain blissfully ignorant of both of these things.

Also in grand dependency injection mindset fashion, we want this producer proxy (my term, incidentally, not CDI’s) to not look up or acquire or otherwise scrounge around for its relevant producer(s).  We want it to simply declare somehow that it needs one, and then punt the problem of getting one to its caller (we’ll talk about who that might be in a moment).

CDI implements this producer proxy concept with a construct called a Context and it is the first CDI construct we’ll look at in depth.

Contexts…

The first thing to know about a Context is that as a CDI end user you’ll interact with it many, many times—and as a consumer you’ll never see it or know that’s what you’re doing.

A Context, in other words, is part of the internal CDI plumbing by which automatic wiring between producers and consumers is implemented.

A Context is the nexus where a consumer needing an object of a certain kind is wired in an abstract fashion to a producer that is capable of producing objects of that kind, and where the lifecycle of such a produced object is managed.

Inside the depths of CDI, when you mark a field or a parameter with @Inject, CDI asks a particular Context for the kind of object you want.  That Context, in turn, ends up asking a producer, when necessary, to make or acquire the kind of object that should go in your @Inject-annotated slot.

From the standpoint of a Context, a producer is represented by something kind of odd called a Contextual.  A Contextual is simply a producer that can also destroy the things it makes.  A Contextual can make any number of different things of a given type (so, for example, a Contextual whose type parameter is Object could make Gorp, Chocolate, PeanutButter or whatever).  Most of the time, though, a given Contextual makes one kind of thing.

Finally, a Contextual should not have, as its core concern, or any concern if at all possible, how long an object should live—it is a “pure” producer: it just makes ’em, ma’am, it doesn’t hang onto ’em.

Here is what the contents of the Contextual interface look like, in their entirety, and for now we can ignore the second of these two methods:

I hope you can see how simple that is.

Contextual is another one of those interfaces that is in the internals of CDI.  You rarely, if ever, implement it directly.  But you could.  And you do in some cases, usually indirectly, as we’ll see much later.

For example, ignoring CreationalContext—a subject for a later post—you could see that you might implement the create method in such a way that it wraps a constructor invocation (you’d be implementing a producer that is constructor-based).  Or you could see that you could implement the create method in such a way that it wraps a method invocation (you’d be implementing a producer that is method-based), though consuming other dependencies in this case might be a little trickier.  Or a field access.  And in many cases your destroy implementation might not have to do anything.

The takeaway here is that you can represent all producers as Contextuals of a particular kind.

Context, then, uses Contextuals to produce the objects it will then manage the lifecycle of.  Here are the (relevant at the moment) contents of this interface, and trust me when I tell you that for now we can ignore the second method:

Again, very simple.

The first method is the real workhorse.  It takes in a Contextual and a CreationalContext, as you can see.  Once again, we’ll ignore the CreationalContext.  (The second method is for certain cases where CDI wants to ensure that no creation at all happens: it just wants the Context to supply a cached instance if one exists; it doesn’t want the Context to make a new one.  We’ll ignore it for the sake of mental clarity.)

The first method’s contract is to acquire and return a T.  You’ll note that Context itself is not a parameterized type (it doesn’t have any angle brackets or type parameters in its name).  So you can see here that a Context can get a whole variety of different kinds of objects.

You can also probably squint and see that if I tell you (as I have) that a Context‘s responsibility is to manage the lifecycle of objects, not actually make them, then when it decides that it needs a new one it can (and should) just call the create method on the Contextual that has just been handed to it.  The Context knows “when”; the Contextual knows “how”.

If it already has an existing instance and has determined that this incoming demand can be satisfied by the existing instance, well, then it can just hand it back.

That’s all very convenient.  So a Context as a consumer remains blissfully ignorant of what kind of Contextual (producer) has been handed to it, and can use this raw material if it wants in order to fulfill its contract of supplying T instances.  And the Contextual can remain blissfully ignorant of lifecycle and caching concerns and can just return Its Thing™, whatever that might be, when asked to make it.

…and Dependency Injection

CDI stands for Contexts and Dependency Injection.  And now with the introduction of Contexts we have an incomplete and blurry view—but a view nonetheless—of how the major parts work together, and why “Contexts” is important enough to be listed in the title of the specification:

  • A consumer of some kind (your business-critical class) gets wired in some currently opaque-to-us way (involving @Inject) to a Context implementation that supplies it with the dependency it needs (via the Context#get(Contextual, CreationalContext) method).
  • The Context implementation gets wired in some opaque way to a Contextual implementation that knows how, but not necessarily when, to make those kinds of things.
  • A Contextual is a kind of producer but everybody but the Contextual implementation itself doesn’t know what kind.

The result is that CDI is now conceptually capable of injecting dependencies, taking into account desired lifecycles, and letting producers and consumers and producer proxies all focus on what they do best, and on nothing else.

Contextual Instances

I’ve spoken very loosely about producers making things of a particular kind.  And I’ve spoken equally loosely about consumers needing things of a particular kind.  And I’ve spoken just as loosely about the wiring process where a producer of a thing of a particular kind gets wired in some fashion to a consumer that needs those things, mediated by a producer proxy—a neutral term I invented to describe the lifecycle/lifespan-managing component that decouples when something is handed out from how it is made or acquired.

Now we’ve also learned that producers in CDI are represented by Contextuals and are effectively “fronted” by Contexts, and that producer proxies are represented by Contexts, and that Contexts therefore are the sources of instances that producers—Contextuals—make.  Consequently when a Context‘s get method hands you (indirectly) an object, that object is known throughout CDI’s literature as a contextual instance.  It is an instance of something that a given Context manages.

Still speaking loosely, when you ask for a Gorp to be supplied to you (injected) by CDI by using the @Inject annotation, you’re going to get a contextual instance of Gorp in the annotated “slot”.

Or, equivalently: if an object “comes out of” a Context, then it is a contextual instance, and its existence must be owed to the fact that CDI invoked get on a Context and the Context ultimately invoked the create method of a Contextual that produced it.  CDI “knows about” all contextual instances.  CDI does not know about (for the most part) objects that are not contextual instances.

In the next post, we’ll look at the mechanics of how CDI wires Contextual implementations that can make certain contextual instances of particular kinds to Context implementations that implement a lifecycle, and how CDI wires consumers of contextual instances to Context instances that can provide them.

A CDI Primer: Part 0

So many tutorials about CDI have been written I’m a little nervous putting down my own.  But here we are.

I believe that most of the CDI articles and posts I’ve read over my many, many years of programming don’t follow the right road for developers just starting out with CDI.  As a result, people think of CDI as magic.  Because its terminology is also unusual, misconceptions get built upon at the earliest stages of learning and you end up with developers sticking beans.xml files everywhere in a prayer to the gods to get their stuff to somehow work.

I also want to try to get the high level concepts in place first before diving deeper.  As a result, I’m going to speak a bit fast and loose here to start with.  My hope is that over time these foundations will demystify the great CDI machine.

Lastly, I’m primarily focusing on CDI alone, i.e. not on any aspect of its integrations with technologies like Java EE.

Let’s dive in.  We’ll start with a section that deals with CDI and @Inject, since that’s how most people first encounter CDI, but then we’ll move rapidly on to the dependency injection mindset, which is much more important.

CDI Makes @Inject Work

For anyone wondering “what is CDI? Why would I use it?” the quickest answer that makes immediate sense is:

CDI is the magic machine that lets you use @javax.inject.Inject.

OK, so why would I use @Inject?  What does it do for me?

Field Injection

Let’s say you have an instance field in your class, and you want it magically set to something, regardless of whether it’s public, protected, package-protected or private.

Do this:

@Inject // magic!
private Gorp myGorp;

CDI makes that work.

That is, some Gorp instance (we’ll talk about which one, and where it came from, in a bit) will get put there by CDI.  Cool!

Think a bit about this: you didn’t have to go hunting around for a Gorp instance yourself.  You didn’t have to look up what kind of Gorp to make from a properties file or JNDI or ServiceLocator or anything like that.  You asked for a Gorp, and a Gorp was delivered unto you from outer space.  Nice.  Simple.  Less of your code; therefore fewer bugs that will be assigned to you.  A smaller mental model: fewer second- or third-order concepts in your head means more clarity in programming the important stuff you need to do.

Injection is the overall term for this kind of magic: something comes along (CDI in this case) and injects a Gorp into, in this case, an instance field of your (business-critical, of course) class.  The thing that is being injected is a dependency: it’s something you need for some reason, so therefore whether you like it or not you depend on it.

So when you get a dependency injected into something, you have dependency injection.

We’ll call this particular case of injection field injection.

Where else can you use @Inject?

Method Parameter Injection

When CDI is in the world, you can also use @Inject on methods.  It’s the same kind of thing.  If you do this:

@Inject
private void consume(final Gorp gorp) {
  // nom nom
}

…the gorp “slot” will be filled with a Gorp instance (as before, we’ll talk about which one, and where it came from, and when in a bit) by CDI.  This is often referred to as setter injection, or setter method injection, or parameter injection, and you might think your method therefore has to be named something like setGorp, but it can be named anything.  The important part is that @Inject “goes on” the method.

Methods with @Inject “on” them can have as many parameters as you want.  CDI will try to “fill” all of them.  So if you do this:

@Inject
private void consume(final Gorp gorp, final Cheese cheese) {
  // nom nom nom nom
}

…CDI will “fill” the gorp “slot” with a Gorp instance, and the cheese “slot” with a Cheese instance.

Constructor Parameter Injection

CDI also makes @Inject on constructors work.  Constructors can be public, protected, package-private or private.  Just as with methods, @Inject-annotated constructors’ parameter “slots” will be “filled” by CDI.  So if you do this:

@Inject
private Chocolate(final PeanutButter peanutButter) {
  super();
}

…the peanutButter “slot” will be filled by CDI with a PeanutButter instance.

Making @Inject Work Is a Kind of Dependency Injection

This style of programming is lumped under the term dependency injection.  The idea is that you, the programmer, never look up or make or seek or acquire what you need (your dependencies).  Instead you “take in” what you need.

You force your caller to hand you your raw materials instead of hounding off and scavenging them yourself.  Always be lazy!

So if you’re writing a Chocolate, and you need a PeanutButter, you do not do this:

// Here is an example of a class that is *not* using
// dependency injection.  It is brittle and hard to test.
public class Chocolate {

  private final PeanutButter peanutButter;

  // Note that the constructor doesn't "take in" anything.
  // Yet the peanutButter field still needs to be "filled".
  // I wonder how that will happen?
  public Chocolate() {
    super();
    // You've seen this kind of thing in your job before.
    // There's the magic "look up the thing" method.
    // My experience has been that LDAP is usually involved. 😃
    this.peanutButter = lookupPeanutButter();
  }

  // Here is the magic "look up the thing" method.
  private PeanutButter lookupPeanutButter() {
    // Almost always there's LDAP or a singleton being used. 😞
    final GroceryStore singleton = GroceryStore.instance();
    // When this lookup breaks, was it because the GroceryStore
    // couldn't be found? or the PeanutButter? You will see
    // anti-patterns like this throughout enterprise Java
    // programming.
    return (PeanutButter) singleton.get("Peanut Butter");
  }

}

In the class above, really what you need is a PeanutButter.  It doesn’t really matter where it came from, just that you “take it in”.  So whether or not you’re ever going to use CDI or Spring or anything else, please write your class like this instead:

public class Chocolate {

  private final PeanutButter peanutButter;

  public Chocolate(final PeanutButter peanutButter) {
    super();
    this.peanutButter = peanutButter;
  }

}

What’s nice is that your class has now punted the problem of how to acquire the PeanutButter to the caller.  Now the caller has to figure that out.  Your Chocolate class is much simpler and easier to deal with.  As someone experiencing the glories of your world-changing code for the first time, I can understand it better and marvel more at your brilliance.

If, on top of this well-designed class, you now put @Inject in the right place, then CDI’s magic can supply—inject—the PeanutButter.  That is, CDI becomes the caller:

public class Chocolate {

  private final PeanutButter peanutButter;

  // Let's use constructor parameter injection
  @Inject
  public Chocolate(final PeanutButter peanutButter) {
    super();
    this.peanutButter = peanutButter;
  }

}

The Dependency Injection Mindset

Now kindly forget CDI for a moment (and Spring if you’re coming from that background).

What is really important here is the mindset.

That mindset is: in any class you’re writing, take in only what you need to get your job done.  Pare it down more and more and more until you truly have the object you need.  Always be lazy; make your caller do the work of finding your dependencies!

Try if you can to pass them in in the constructor of your class and set them in private final instance fields.  Immutability is good!

The more you relentlessly and recursively pursue this mindset, the simpler your classes will be and the more clear the dependencies between them will be.

The fact that some of them might be “injected” by some kind of magic machine like CDI is utterly immaterial to your class design.  The dependency injection mindset is much more about the “dependency” part and much less about the “injection” part.

If there’s one thing you take away from this series of articles, let it be that programming using the dependency injection mindset—even if you never use a dependency injection framework like CDI (or Spring, or Jersey’s HK2)—is its own goodness.

Consumption

Within the dependency injection mindset, there are consumers and producers.

Consumers are like the Chocolate class above: they “take in” stuff, do their work, and are done.  A good consumer declares dependencies on exactly what it needs and doesn’t worry about how that stuff gets made or supplied or looked up or acquired.  In CDI, using @Inject at some location indicates that you’re doing consumer work there.

Consumption is the heart of the dependency injection mindset.

Production

Up to this point we’ve been focused on not worrying about where, for example, instances of PeanutButter come from or who makes them or how many little subassemblies go into ultimately manufacturing one.  All of these concerns are part of production.

For this article, a producer is something whose primary job is “handing out” an instance of something.  Sometimes “handing out” means “creating”, and sometimes it means acquiring or looking up.

Sometimes a producer “knows” it should hand out the same thing over and over again.  If you’ve programmed in Java for any length of time, you’ve run into someone somewhere who uses singletons and methods to hand them out.  These methods that return singletons are doing production work—they’re producers.

If you squint right, and look at things a certain way, another kind of producer that hands out the same thing over and over again is a field!  So looked at under the right lights, a field can be a producer.

Other times a producer “knows” it should hand out a new thing whenever called for.  Again, if you’ve been in the Java enterprise world for a while you’ve seen various Factory-suffixed classes.  Typically they have methods that start with create or make or get and they create or make something (often times a thing whose class is named the same thing as the factory class, minus the Factory suffix) and return it whenever they’re invoked.  These methods too are producers.

These kind of method-based producers obviously live “inside” classes (they’re methods, after all).  The things they make may or may not be instances of the classes the producers live inside.  For example, a PeanutButterFactory class may contain an acquirePeanutButter method that returns a PeanutButter instance.  Note that the class that houses the PeanutButter producer—PeanutButterFactory—in this case is not the same as the class of the return type of the method—PeanutButter.

Just so we can talk about things later let’s call the “housing” of a producer (whether it’s a field or a method) a producer class.  As we’ve seen above, in general—but with one notable exception described immediately below—the class of the thing being made (the field’s type, or the method’s return type) need not be the same as the producer class housing the producer (the field or the method) that makes the thing.

Finally, there are producers all over the place in plain sight that you may not think of.  They create new things every time when called for.  They’re called constructors!  Constructors have an interesting property, which is that they must be housed in the class that is the class of the instances they make.  So, for example, a PeanutButter constructor makes PeanutButter instances and can’t make anything else.

Another way to put this is that in the case of constructors, the producer class’ producer (the constructor) makes instances of the producer class itself.

So fields, methods and constructors are all producers if you look at them as sources of objects that someone might need.

Production and Consumption

Oftentimes, a method or constructor that is making or getting things to hand to a caller will need other raw materials to get the job done.  Maybe, as in our examples earlier, a producer of PeanutButter instances needs to get them from a GroceryStore.

Following the dependency injection mindset, there’s nothing to prevent a producer from also being a consumer!  That is, a method that for various business-related reasons returns or creates a PeanutButter instance from a GroceryStory shouldn’t look up a GroceryStore instance, or set about some other means of creating a GroceryStore, it should simply declare that it needs one.

Here’s what a PeanutButter-returning producer (method) might look like when it’s designed from within the dependency injection mindset.  Note that there’s no GroceryStore acquisition going on (no singletons, no LDAP, no database servers, no configuration subsystem):

public PeanutButter acquirePeanutButter(final GroceryStore store) {
  return store.get("Peanut butter");
}

Note that this method is a producer when we’re looking at it as a source of PeanutButter instances, and a consumer when we’re looking at it as something that needs a GroceryStore to do its job.

Wiring It Up

Suppose now we’ve written several classes using our dependency injection mindset.

So in our left hand we have consumers that need things to do their job.  In our right hand we have producers that make things should they ever be needed by someone (and may also consume things as part of that production process).

We can tell just by surveying the landscape that that method over there that returns PeanutButter instances—a PeanutButter producer—”goes with” this consumer over here, Chocolate, whose constructor needs PeanutButter instances.

Again, just by looking at things, we can see that if we wanted to ever instantiate a Chocolate for any reason, we’re first going to need a PeanutButter.

To get a PeanutButter, we’re going to have to call that PeanutButter-returning method.

To call that PeanutButter-returning method, we’re going to have to create an instance of the class it “lives” in, then…oops, we’re going to need a GroceryStore because—remember? see the examples above—the PeanutButter-returning method needs a GroceryStore to do its job.  So we’ll need to recursively go through this effort with GroceryStore—maybe it in turn is produced by a producer, or maybe we can just call its constructor.

This process of figuring out these relationships and instantiating the right things in the right order in order to come up with other things is known generically and colloquially as wiring.  You can do it by hand.  It’s not magic.

Wiring By Hand

For example, at the initialization of our program somewhere we could do something like this (this example deliberately has a few problems):

final GroceryStore groceryStore = new GroceryStore();
groceryStore.put("Peanut butter", new AdamsChunky());
final PeanutButterFactory factory = new PeanutButterFactory();
final PeanutButter peanutButter = factory.acquirePeanutButter(groceryStore);
final Chocolate c = new Chocolate(peanutButter);

This is an example of (deliberately slightly bad, but not awful) wiring by hand, but it shows wiring nonetheless.

We’ve made many choices here.  Some are obvious; some, when generalized into your enterprise project of choice beyond this stupid example—swap in your favorite system you love to hate in place of GroceryStore, for example—are perhaps not so easy to see:

  • We’ve chosen the kind of GroceryStore.
  • We’ve chosen the kind of PeanutButter.
  • We’ve explicitly said that our PeanutButter instance, regardless of what choice we made a line above, is going to come out of a GroceryStore.
  • We’ve also said that PeanutButter instances can be acquired from a factory method.  (Hmm; can that method be subclassed?  Are there now two “sources of truth” or more for PeanutButter instances?)
  • We’ve implied that PeanutButter instances are (effectively) singletons.  Maybe we didn’t mean to do this.  Maybe this matters; maybe not.

So we’ve deferred certain choices—a Chocolate takes in a PeanutButter, but isn’t choosy about what kind, or where it came from; a GroceryStore presumably allows you to put any kind of PeanutButter you like; we’ve abstracted the production of PeanutButter behind a black-box method (acquirePeanutButter)—which is nice.  But it is important to note that we’ve wired in many other hardcoded choices above.

Many enterprise projects will have something like this, and a well-meaning developer will say, ah, hardcoding is bad; let’s allow someone to configure the kind of PeanutButter to use so it isn’t always AdamsChunky.  So they introduce a configuration file or mechanism that looks up the kind of PeanutButter to use—and now we’re out of the dependency injection mindset.  Oops!

That is: there will now be code in this initialization sequence that requires a certain configuration mechanism to look up the precise type of PeanutButter required.  Then someone will come along and try to abstract that configuration mechanism.  These are instances of slightly buried service locator patterns applied intentionally and unintentionally in the initialization code—and then suddenly it turns out that for reasons no one is entirely sure of you have to have an LDAP server or database running in order to test a Chocolate instance.  Ugh!  What happened to our “just declare the thing you need”?

And where does CDI come in?

Automatic Wiring

CDI is that well-meaning developer, and the author of the initialization code above, but way better: it does the wiring correctly, automatically and well without interfering with the dependency injection mindset.  As you can probably see by now, that initialization code is the process of matching producers with consumers, and that is exactly what (this area of) CDI does.  It has been doing this work correctly and well for many, many years.

Armed with this foundation (the dependency injection mindset, seeing the world in terms of producers and consumers and a middle-player that wires them together properly and efficiently), we can move on in the next post to how CDI does this.

Maven Specifications and Environments: Part 2

In the previous post, we looked at the concept of environments—implementations of specifications (a concept discussed two posts ago).

When you have a Maven project that you want to be runtime-independent, but coded to a particular JCP specification, things get a little hairy. Your code must compile against an API jar (or API jars, or, if you’ve read this series of posts, a specification), but you want it to run at test time against a particular environment, and you want that environment to dictate which API jars should be used.

This sounds like a contradiction until we realize that Maven respects the order in which <dependency> elements are listed.

The TL;DR here is: when you are putting together your <dependency> elements, list them in your pom.xml in typically reverse order: list test-scoped dependencies first, then runtime-scoped dependencies, then provided-scoped dependencies and finally compile-scoped dependencies.

Why?

When you compile, none of the test-scoped dependencies will be “in scope”, so they will simply be ignored. Next on the classpath will be your provided-scoped dependencies followed by your compile-scoped dependencies. At compile time, none of this really matters: where your provided-scoped dependencies appear on your classpath is typically irrelevant.

But when you test, the order is suddenly quite important. If your test-scoped dependencies come first, then any transitive API jars that they pull in (for example) will be the ones that are actually used on your classpath—they’ll “come before” any provided-scoped API jars you have in order to support runtime environment-independent compilation. Those provided-scoped dependencies will still be on your classpath at test time, but they’ll never be referenced: the runtime environment you’re testing against should (must!) dictate its own API jars to be used, so those are the ones you’ll end up using.

To make this slightly more concrete, let’s say you have a CDI project and you want to be able to run it on either Weld or OpenWebBeans. Let’s say further that you’re going to run unit tests using Weld. Now recall that Weld uses the JBoss-authored version of javax.interceptor packages reified in the org.jboss.spec.javax.interceptor:jboss-interceptors-api_1.2_spec:jar artifact, not the javax.interceptor:javax.interceptor-api:jar artifact. To preserve runtime environment independence, you want to compile (let’s say) against the javax.interceptor:javax.interceptor-api:jar artifact, but when you test with Weld you want Weld to use whatever API jars it wants, not the runtime-environment-independent ones you happen to have selected and compiled against.

To do this, you’ll add Weld first in test scope, then javax.interceptor:javax.interceptor-api:jar in provided scope. When you compile, you’ll use javax.interceptor:javax.interceptor-api:jar; when you test you’ll end up transitively using javax.interceptor:javax.interceptor-api:jar.

When you expand this strategy to include environments and specifications as defined earlier in this series of posts, component-oriented development becomes much simpler.

Maven Specifications and Environments: Part 1

In the previous post, we took a look at specifications: Maven pom.xml files that represent pom-typed artifacts that house dependencies in compile scope, but are themselves depended upon in provided scope.

Specifications give you the artifacts you need to compile your code. But (if built properly) they don’t come with implementations. This lets your code be coupled to, say, the CDI specification without being coupled to, say, Weld (instead of, say, OpenWebBeans).

I’ve settled on the term environment to describe another Maven pattern I use to back a particular specification with the jars needed to implement it. The challenge here is that a given environment is—like the specification it implements—comprised of many jars. To reduce boilerplate, we want to find a good way to declare our runtime dependence on various jars that implement the classes and interfaces defined by the API jars our code relies upon during compilation.

Another challenge is that strictly speaking an environment often correctly and legally brings in its own implementations of API jars. For example, Weld does not depend on javax.interceptor:javax.interceptor-api:jar (which houses the javax.interceptor packages that reify the interceptors specification), but on org.jboss.spec.javax.interceptor:jboss-interceptors-api_1.2_spec:jar. This jar file also houses the javax.interceptor packages that reify the interceptors specification. This plurality of API jars reifying the same (English) specification is entirely legal, but you should only have one API jar at runtime, and the runtime (Weld, OpenWebBeans) should pick it (org.jboss.spec.javax.interceptor:jboss-interceptors-api_1.2_spec:jar, javax.interceptor:javax.interceptor-api:jar). That is, at runtime you want the runtime environment to dictate which API jars are actually on the classpath, not your own Maven pom.xml file.

The idea behind an environment as represented by a pom.xml file is basically the same as that of a specification as represented by a pom.xml file. You define your pom.xml to have a packaging type of pom, and you list your elements, but this time you put them in runtime scope. Then you depend on this new environment by depending on it in runtime scope. The net effect is that its runtime-scoped dependencies become your project’s transitive dependencies in runtime scope.

Note that an environment defined like this doesn’t (necessarily) depend on a specification as we defined it in the previous post. An environment always supplies what it needs, and code designed to run in any environment of a particular kind is compiled against a specification as defined in the prior post.

Environments can be composed, and can be abstract or concrete. Here’s an example of one of the environments I use in my microBean projects. It is abstract, in the sense that it sketches out a modular runtime but lacks a CDI implementation. It does, however, specify a javax.validation implementation (Hibernate) and a Java Expression Language implementation (Glassfish):

Here is another example of an environment that I use in my microBean projects that uses the abstract environment above:

Line 85 is where we pull in the abstract environment. Note that it is in runtime scope. That means we pull in everything that environment defines, as well as whatever else is listed here. The end result is the contents of that abstract environment, plus the Jandex runtime, a SLF4J logging binding and Weld itself. At line 76, you can see that because the abstract environment has already pulled in a runtime implementation of the Java Expression Language, it by definition has supplied its own EL API jar, so we want to make sure that that is the API jar in use for that specification, so we exclude JBoss’ EL API jar here.

Once this environment has been defined, then we just have to use it. Let’s say we want to build a program that will run in this environment. In our project’s pom.xml, we would simply do this:

The last remaining hurdle is testing. Even when compiling code against a specification, you often want to test it in one of possibly many environments. When you do this, you want to make sure you’re testing against the environment and its dependencies, and not the provided-scoped specification that you’re compiling against. (Often the differences are merely academic, but not always.) We’ll look at this in the next post.