Dependency Injection is the most important concept of the Spring. It is also called as Inversion of Control (IoC). Dependency Injection makes our code Loosely Coupled, Spring’s IOC container is light-weight and it manages the dependency between objects using configurations. It connects the related objects together, instantiates and supplies them based on configuration. Spring DI can be configured in two different way XML Based (Spring-configuration xml) and Annotation based.
Spring Dependency Injection Types
Dependency Injection can be classified into three main types
- Setter Injection
- Constructor Injection
- Interface Injection
In this article, we will look at how the Setter Injection Works.
Create a simple Java project with the below files.
SetterBean.java
package com.javainterviewpoint; public class SetterBean { String text; public String getText() { return text; } public void setText(String text) { this.text = text; } public void disp() { System.out.println(text); } }
ClientController.java
package com.javainterviewpoint; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class ClientController { public static void main(String args[]) { Resource resource = new ClassPathResource("SpringConfig.xml"); BeanFactory beanFactory = new XmlBeanFactory(resource); SetterBean setterBean = (SetterBean)beanFactory.getBean("bean1"); setterBean.disp(); } }
Spring Configuration File
Place the SpringConfig.xml under the src directory of your project.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="bean1" class="com.javainterviewpoint.SetterBean"> <property name="text" value="Welcome to Spring Setter Injection" /> </bean> </beans>
How Setter Injection Works here :
- In the SetterBean.java I have written a setter for the property “text”, spring will inject the value to it in the runtime.
- First, create a Resource object which will help to read the configuration file.
- Feed the resource object to the BeanFactory, so that the factory knows the beans which are available in the configuration file.
- We have added the value to the property “text” in the xml file.
<property name="text" value="Welcome to Spring Setter Injection" />
- Through the getBean(“bean1”) call we get the object of the SetterBean, which has access to the disp() method.
SetterBean setterBean = (SetterBean)beanFactory.getBean("bean1"); setterBean.disp();
This is all about Setter Injection in Spring
Leave a Reply