Quote

We are what we repeatedly do. Excellence, therefore,is not an act but a habit.

Aristotle

Wednesday, January 6, 2010

Constructor Injection DI

Constructor-based DI is effected by invoking a constructor with a number of arguments, each representing a dependency.

______________________________________________________________________________________


public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

private int i;

public ExampleBean(

AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

this.beanOne = anotherBean;

this.beanTwo = yetAnotherBean;

this.i = i;

}

}


_____________________________________________________________________________________




<bean id="exampleBean" class="examples.ExampleBean">

<!-- constructor injection using the nested <ref/> element -->

<constructor-arg><ref bean="anotherExampleBean"/>

</constructor-arg><!-- constructor injection using the neater 'ref' attribute -->

<constructor-arg ref="yetAnotherBean"/><constructor-arg type="int" value="1"/></bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>

<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>


____________________________________________________________________________________

No comments:

Post a Comment