What does the Spring framework do? Should I use it? Why or why not?
Spring is a framework that helps you to "wire" different components together. It is most useful in cases where you have a lot of components and you might decide to combine them in different ways, or wish to make it easy to swap out one component for another depending on different settings or environments.
This is what I've always understood "dependency injection" to be.
I would suggest a different definition:
"Dependency injection is where you design your classes so that they expect an outside actor to directly give them the sub-tools they need to do their jobs before anybody starts asking them to do something."
Most of the XML (or annotation-based) stuff is telling spring:
- When someone asks for a "HammerStore", I want you to create a
example.HammerStore
and return it result. Cache the result, since there is only one store. - When someone asks for a "SomeHammer", I want you to find a "HammerStore" and return the result of its
getHammer()
method. Do not cache the result, but make a new hammer each time. - When someone asks for a "SomeWrench", I want you to create a
example.WrenchImpl
and take the configuration settingguage
and put it into thesetWrenchSize()
property. Do not cache the result, but create a new one each time. - When someone asks for a "OurPlumber", I want to you create an instance of
example.PlumberImpl
. Put the string "Pedro" into itssetName()
method, put a "SomeHammer" into itssetHammer()
method, and put a "SomeHammer" into itssetWrench()
method. Return the result, but do cache it, since we only have one Pedro.
In this way, Spring lets your connect components, label them, control their lifecycle/caching, and alter behavior based on configuration.
To facilitate [testing] I typically make (at least) two versions of a method : one that uses instance variables, and one that only uses variables that are passed in to the method.
That sounds like a lot of overhead for not a lot of benefit for me. I would suggest that you make your instance variables
protected
or package-level, and then locate the unit tests inside the same package. That way you can alter or test the instance variables in-place.
No comments:
Post a Comment