DI comes in three common forms: setter injection, constructor injection, and interface
injection. The setter injection form looks like this:
public class MyClass {
private MyBean bean;
public void setMyBean(MyBean inBean) {
this.bean = inBean;
}
}
When an instance of MyClass is instantiated via the IoC container, the container will
create an instance of MyBean and call setMyBean() on the MyClass instance before any other
methods are called. Very nice??”all the other methods can then go ahead and use MyBean
without having to have constructed the instance itself. Consider if MyBean required some
complicated construction, for example, a bunch of fields set a certain way and things of that
nature. Isn??™t it nice to not have had that code in MyClass? This type of setup of an injected
object will generally be done via some formof configuration file, or annotations, so it??™s
abstracted out from the code that is making use of it.
Another form of DI is constructor injection:
public class MyClass {
private MyBean bean;
public MyClass(MyBean inBean) {
this.bean = inBean;
}
}
It??™s not much different from setter injection, so it pretty much comes down to a matter of
which code you prefer.
Pages:
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588