Java & J2EE Page 2 - The Spring Framework: Understanding IoC |
The central aspect of the Spring Framework is the configuration file, as all the details of the POJOs as well as connecting them with the required services is done in the configuration file. Using different forms of IoC is also no exception. The declarations in the configuration file decide which form of Dependency Injection the container uses. This section will focus on the required declarations in the configuration file. The POJO that will be used throughout this section will be a simple greeting bean that will get the user’s name and return the string “Greeting” added to the user name. The GreetingBean class is as follows: public class GreetingBean { private String userName; public GreetingBean() { } public GreetingBean(String a) { userName=a; } public String sayhello() { return “Greetings “+userName; } public void setUserName(String a) { userName=a; } } Now let us see how to use the different forms of Dependency Injection with Spring Framework. Constructor Injection To use constructor injection, the required declaration is done in the bean section of the configuration file that is the beans.xml file. The steps to use Constructor Injection are setting the constructor declaration and passing the value to the constructor. Setting the constructor declaration tells the container that the application wants to use the Constructor Injection. The declaration is done using the <constructor-arg> child element of <bean> element. For example, to use the Constructor Injection for a POJO named GreetingBean the code would be: <bean id=”GreetingBean” class=”org.me.GreetingBean”> <constructor-arg> : : </constructor-arg> </bean> The next step is to pass the value to the constructor. To do this, the <value> element of the <constructor-arg> has to be used. The value to be passed is given as the value of the <value> element. For example, to pass “Raj” as username, the code would be: <bean id=”GreetingBean” class=”org.me.GreetingBean”> <constructor-arg> <value>Raj</value> </constructor-arg> </bean> That completes the steps for using Constructor Injection. Next we will look at how to use the Setter Injection.
blog comments powered by Disqus |
|
|
|
|
|
|
|