I come from a .NET background, using dependency injection containers like Unity, Ninject, Castle Windsor, etc. Recently I have begun to learn to use Spring’s dependency injection capabilities for Java.
In learning Spring, I’ve seen that it’s possible to specify on a bean XML configuration the notion of an ‘init-method’ and ‘destroy-method’.
The purpose of specifying an ‘init-method’ appears to be to do any setup at bean creation time that you might want to do. Here’s where I get confused. Why would you need a separate method to perform setup, instead of just using the constructor to perform any setup needed by the object, like normal/good object oriented design would dictate?
In other words, if a dependency is required by a class, shouldn’t it be injected in the constructor, which you know has been called, whereas the object could exist in a state without having called it’s ‘init-method’ ?
There are few cases where separate
init()method is needed:legacy APIs where you just don’t have any choice
initialization having some side-effects, e.g. starting a
Thread, connecting to som external resourcesThis actually has even deeper implications: when using class-based proxies (via cglib) constructor of your base class is called twice (second time for the proxy that inhertis from your class) –
init()method is called only once on final object.you shouldn’t perform virtual calls in constructor (this should actually be forbidden by the compiler…)
sometimes you must use setter/field injection (although I love constructor injection), e.g. when aforementioned class-based proxies are used
This isn’t actually the best practice to put all initialization code in constructor. Side-effects in constructor make testing and mocking much harder. Instead focus on creating objects in stable and known state. This way you can e.g. decouple creating an object managing the connection pool and physically connecting to that pool.
BTW
destroy()is a blessing in a language without destructors as it allows you to gratefully close external resources, interrupt threads, etc. Use it often.