Spring Constructor Dependency Injection

Here I show you how spring container injects the value to the constructor parameter during run-time with reference from spring configuration file.

Constructor Dependency Injection

public class Rectangle {

private String type;

@Description("Spring container will inject the parameter value to this constructor"
+ "during runtime with reference from configuration file")

public Rectangle(String type) {
this.type = type;
}

public void draw() {
System.out.println(getType());
}

public String getType() {
return type;
}

//NOTE: There is no SETTER method for the variable 'type'
}

spring.xml configuration file

<beans>
<!– Constructor Dependency Injection Demo –>

<bean id=”rectangle” class=”com.saravanansivaji.spring.Rectangle”>
<constructor-arg value=”Rectangle drawn!!”/>
</bean>
</beans>

SpringDI.java application class

public class SpringDI {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

@Description("Constructor Dependency Injection Demo")

Rectangle rectangle = (Rectangle) context.getBean("rectangle");
rectangle.draw();
}

}

Output
Rectangle drawn!!

Thanks!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: