concept string key in category dependency injection

appears as: string key, string keys
Dependency Injection: Design Patterns Using Spring and Guice

This is an excerpt from Manning's book Dependency Injection: Design Patterns Using Spring and Guice.

Figure 2.12. Organizing string keys into namespaces

String keys are flexible, and if chosen well they work well. But well chosen or not, string keys have limitations that can be confounding and rather, well, limiting! Let’s talk about some of them.

Misspelling the annotation name results in a compiler error, which is an early and clear indication of the problem. This is exactly what we were after. What we have done is effectively replace the string key with a second type key. In combination with the service’s type key, this retains the qualities of good behavior in well-chosen keys but also eliminates the problems posed by arbitrary, abstract strings. This is quite a comprehensive and elegant solution. The fact that annotations can be reused also makes them good for more than the one service:

[Emailer.class, English.class]
[Dictionary.class, English.class]
[SpellChecker.class, English.class]

We use the @English annotation to distinguish variant implementations of not only the Emailer but also the Dictionary and TextEditor services. These keys are self-documenting and still give us the flexibility of a string key. Since annotations are cheap to create (hardly a couple of lines of code) and reuse, this approach scales nicely too.

2.4.2. Limitations of string keys

String keys are inherently problematic when one factors human error into the equation. We have all been there. Take the possible ways to spell a common name, for example:

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest