
Oleh : Reza Ervani
بسم الله الرحمن الرحيم
scope prototype :
Jika scope diset ke prototype, kontainer IoC Spring membuat instance bean yang barus setiap kali permintaan untuk bean tersebut diterima. Jadi, gunakan scope prototype untuk semua bean yang bersifat state-full dan gunakan scope singleton untuk bean yang bersifat stateless
Untuk mendefinisikan scope prototype, kita dapat menset properti di file konfigurasi bean seperti berikut :
1 2 3 4 | <!-- Definisi bean dengan scope prototype --> < bean id = "..." class = "..." scope = "prototype" > <!-- kolaborator dan konfigurasi bean ditempatkan disini --> </ bean > |
Contoh :
Taruh kata kita menggunakan Eclipse IDE dan mengikuti langkah-langkah berikut untuk membuat aplikasi Spring :
- Buat sebuah project dengan nama ContohSpring dan buat paket com.eclipseprogramming dibawah folder src pada project yang dibuat
- Tambahkan pusataka Spring yang dibutuhkan menggunakan Add External JAR
- Buat class Java HelloWorld dan MainApp dibawah paket com.eclipseprogramming
- Buat file konfigurasi beans Beans.xml dibawah folder src
- Langkah terakhir adalah membuat konten seluruh file java dan konfigurasi Bean dan menjalankan aplikasinya sebagaimana dijelaskan dibawah ini :
Isi dari file HelloWorld.java adalah seperti berikut :
01 02 03 04 05 06 07 08 09 10 11 12 13 | package com.eclipseprogramming; public class HelloWorld { private String message; public void setMessage(String message){ this .message = message; } public void getMessage(){ System.out.println( "Your Message : " + message); } } |
Following is the content of the MainApp.java file:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 | package com.eclipseprogramming; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "Beans.xml" ); HelloWorld objA = (HelloWorld) context.getBean( "helloWorld" ); objA.setMessage( "I'm object A" ); objA.getMessage(); HelloWorld objB = (HelloWorld) context.getBean( "helloWorld" ); objB.getMessage(); } } |
Berikut ini adalah konfigurasi Beans.xml yang dibutuhkan oleh scope prototype :
01 02 03 04 05 06 07 08 09 10 11 12 | <? xml version = "1.0" encoding = "UTF-8" ?> xsi:schemaLocation="http://www.springframework.org/schema/beans < bean id = "helloWorld" class = "com.eclipseprogramming.HelloWorld" scope = "prototype" > </ bean > </ beans > |
Setelah kita selesai membuat sumber dan file konfigurasi bean, mari kita jalankan aplikasi tersebut. Jika tidak ada hambatan maka akan muncul dua pesan berikut ini :
Your Message : I’m object A
Your Message : null
Leave a Reply