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

Contoh.

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){
this.setRectangle(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");

drawing.getCicle().printShape();
drawing.getRectangle().printShape();
}

}

Bean configuration file ( BeanEx.xml )

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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">
<constructor-arg>
<ref bean="rectangle" />
</constructor-arg>

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

</beans>

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: