Home > Java > Spring Bean Autowiring

Spring Bean Autowiring

February 18, 2014 Leave a comment Go to comments

Pada Spring framework, kita dapat wire bean secara otomatis dengan auto-wiring feature. Untuk melakukan tambahkan autowire attibute pada pada <bean>. Spring framework mendukung lima jenis auto-wiring.

  • byName
  • byType
  • Constructor
  • autoDetect
  • none (default)

Contoh

  • Autowiring byName

Circle class

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

Shape class

public class Shape  {
private Circle circle;
public void setCircle(Circle circle) {
this.circle = circle;
}
public Circle getCircle() {
return circle;
}
}

Bean Configuration

...
<bean id="circle"class="com.shape.Circle" />
<bean id="shape"class="com.shape.Shape" autowire="byName"/>
...

Property circle pada Shape class di-inject dengan bean dengan id circle.

  • Autowiring byType

Rectangle class

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

Shape class

public class Shape  {
private Rectangle myRectangle;
public void setRectangle(Rectangle rectangle) {
this.myRectangle = rectangle;
}
public Rectangle getRectangle() {
return myRectangle;
}
}

Bean Configuration

...
<bean id="rectangle" class="com.shape.Rectangle" />
<bean id="shape" class="com.shape.Shape" autowire="byType"/>
....

Property myRectangle pada Shape class di-inject dengan bean dengan type Rectangle.

  • Autowiring constructor

Shape class

public class Shape  {
private Rectangle myRectangle;
public Shape(Rectangle rectangle){
this.myRectangle = rectangle;
}
public Rectangle getRectangle() {
return myRectangle;
}
}

Bean Configuration

.....
<bean id="rectangle" class="com.shape.Rectangle" />
<bean id="shape" class="com.shape.Shape" autowire="constructor" />
.....

Secara umum sama dengan autowiring byType, yaitu men-inject property berdasar tipe property tersebut.  Jika autowiring byType melalui setter injection, autowiring constructor melalui constructor injection.

  • Autowiring autodetect

Autowiring ini bekerja dengan pertama melakukan autowiring constructor. Jika tidak berhasil, melakukan autowiring byType.

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: