Spring Dersleri – PostConstruct ve PreDestroy Kullanımı
Spring Framework Dersleri‘ne devam ediyoruz.
Bu yazıda @PostConstruct ve @PreDestroy anotasyonlarını inceleyeceğiz. Önceki derslerden hatırlayacağınız gibi Spring Bean Yaşam Döngüsü içerisinde InitializingBean – DisposableBean ‘e bakmıştık. (bknz: Buradan) PostConstruct ve PreDestroy anotasyonlarıda aynı işlevi yerine getiren Java EE 6 ile gelen bir anotasyon olup kullanımı da oldukça basit.
Örnekte de göreceğimiz gibi kullanımı yazıda da ifade ettiğim gibi kullanmak istediğim Bean içerisindeki metodumuza @PostConstruct ve @PreDestroy yazmamız yeterli olmaktadır.
Spring içerisinde bu anotasyonları kullanmak için bir örnek yapalım.
public class MesajService { String mesaj; public String getMesaj() { return mesaj; } public void setMesaj(String mesaj) { this.mesaj= mesaj; } @PostConstruct public void init() throws Exception { System.out.println("Inıt Metot PostConstruct : " + mesaj); } @PreDestroy public void preinit() throws Exception { System.out.println("Spring Konteyner Durdu ve preinit metodu çalıştı"); } }
Spring konfigürasyon dosyamızı oluşturalım.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> <bean id="MesajService" class="com.burakkutbay.MesajService"> <property name="mesaj" value="Merhaba Dünya" /> </bean> </beans>
Programı çalıştıracak Main metodu çalıştıralım.
public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Springcontext.xml"}); MesajService msg = (MesajService)context.getBean("MesajService"); System.out.println(cust); context.close(); } }
Bu örneğimizde init metodu ilk olarak çalışacaktır. preinit metodu ise Spring Konteynır’ı durduğu ya da durdurulduğu anda çalışacaktır. Ve gerekli mesajı ekrana yazdıracaktır.
Oldukça kullanışlı olan bu anotasyonları örnekle açıklamış olduk.
Önceki Ders: Bean Yaşam Döngüsü – 2 | Spring Dersleri | Sonraki Ders: Required Anotasyonu Nedir? Kullanımı |
No Comment! Be the first one.