Home > Java > Dependency Injection Pada Spring Framework

Dependency Injection Pada Spring Framework

February 16, 2014 Leave a comment Go to comments

Pada Spring framework terdapat 2 jenis DI yaitu :

1. Setter Injection

2.Constructor Injection


Circle class.

package com.shape;

public class Circle {

public void printShape() {
System.out.println("Circle Shape");



Rectangle class.

package com.shape;

public class Rectangle{

public void printShape() {
System.out.println("Rectangle Shape");



Drawing class.

package com.shape;

public class Drawing {

private Circle circle; //Setter Injection
private Rectangle rectangle; Constructor Injection

public Drawing(Rectangle rectangleIn){
public void setCircle(Circle circleIn){
this.circle = circleIn;

public Circle getCicle(){
return circle;
public void setRectangle(Rectangle rectangle) {
this.rectangle = rectangle;
public Rectangle getRectangle() {
return rectangle;

Main class.

package com.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.shape.Drawing;

public class Main {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("BeanEx.xml");
Drawing drawing = (Drawing)context.getBean("drawing");



Bean configuration file ( BeanEx.xml )

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<bean id="rectangle" class="com.shape.Rectangle" />
<bean id="circle" class="com.shape.Circle" />

<bean id="drawing">
<ref bean="rectangle" />

<property name="circle">
<ref bean="circle" />


Project Structure

Project Structure

Referensi : dari berbagai sumber.

Semoga bermanfaat.

  1. No comments yet.
  1. No trackbacks yet.

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: