Re: DI = XML parser that can resolve references?
On Oct 20, 5:29 am, Olli Plough <oli...@plohmann.com> wrote:
I'm having a look into that Spring stuff and therefore into dependency
injection, of course. Now I'm wondering what's the great catch about
DI. Yes, right, you get around import statements in your code that
reference technology-specific or vendor-specific classes. This is of
course very useful. What I actually already did myself without knowing
about DI was interface-based injection which is an obvious approach I
would say that everyone would find himself. I was skimming my Spring
book from beginning to end and back again and it seems to me that DI
is not much more than that. I mean build a XML parser that can resolve
references to other objects defined in XML and you are basically done
(objects referenced must be programmed against an interface, of
course, to be decoupled).
public class MyBean
EntityManager em = null;
Now when I create an instance of MyBean the variable em is already
set. I don't have to bother how to get a reference to that thing and
am therefore decoupled from the respective JPA provider. How does em
get set now? Seems to me that this must be done when the lookup from
the JNDI-Server (InitialContext) is made. But then I have a dependency
on the JNDI-Server, I'm not really technology independent here.
In a lot of older code (particularly J2EE code), if MyBean needed
(depended on having) an EntityManager, it would create one itself.
Dependency injection is the notion that some external environment will
provide the dependencies, rather than requiring each object to manage
its own directly. That's all. Every DI framework (EJB3, Spring,
various others) is merely an abstraction for making the exact objects
provided as dependencies configurable somehow.
By providing dependencies externally, you can reduce the
responsibilities of objects from "do X, and also manage my
dependencies" to "do X". This tends to make the code more flexible
and easier to test automatically, since you can provide alternate
implementations of various dependencies and rearrange them as needed
without having to rewrite all of the "and also manage my dependencies"
Though I've never heard of anyone doing it, you could write a complete
DI framework using properties files or YAML or some other text, or
even just using Java and hardcoding the dependencies one level up from
the objects that need them. There's nothing specific to XML in the