Dependency injection seems to be a good thing. In general, should dependencies be injected at the methods that require them, or should they be injected in the contructor of the class?
See the samples below to demonstrate the two ways to inject the same dependency.
//Inject the dependency into the methods that require ImportantClass Class Something { public Something() { //empty } public void A() { //do something without x } public void B(ImportantClass x) { //do something with x } public void C(ImportantClass x) { //do something with x } } //Inject the dependency into the constructor once Class Something { private ImportantClass _x public Something(ImportantClass x) { this._x = x; } public void A() { //do something without x } public void B() { //do something with this._x } public void C() { //do something with this._x } }
Constructor injection should be the main way that you do dependency injection. It's simple: A class needs something and thus asks for it before it can even be constructed. By using the guard pattern, you can use the class with confidence, knowing that the field variable storing that dependency will be a valid instance.
Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is a much bigger concern.
The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
The major benefit of constructor injection is that it allows your fields to be marked final. For example:
class Foo { private final Bar _bar; Foo(Bar bar) { _bar=bar; } }
The following page has a great list of the pro's and con's: Guice Best Practices:
Method injection
Constructor injection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With