אביב @PostConstruct ו-@PreDestroy

כשאנו מגדירים Spring Beans באמצעות הזרקת תלות, לפעמים רוצים לוודא שהכל מאותחל בצורה תקינה לפני שהחפץ שלנו מתחיל לשרת את בקשות הלקוח. באותה מידה, כאשר ההקשר נהרס, עשויים להיות צורך לסגור כמה מקורות שנעשה בהם שימוש על ידי Spring Bean.

Spring @PostConstruct

כאשר אנו סימון של מתודה ב- Spring Bean באמצעות הערה @PostConstruct, היא מתבצעת לאחר שה- Spring Bean אותחל. יש לנו אפשרות להכיל רק מתודה אחת המסומנת בהערה @PostConstruct. הערה זו היא חלק מ- Common Annotations API והיא חלק ממודול JDK javax.annotation-api. לכן, אם אתה משתמש בהערה זו ב-Java 9 ומעלה, עליך להוסיף באופן פעיל את ה-jar הזה לפרויקט שלך. אם אתה משתמש ב-Maven, אז יש להוסיף את התלות הבאה לקובץ ה-pom שלך.

<dependency>
	<groupId>javax.annotation</groupId>
	<artifactId>javax.annotation-api</artifactId>
	<version>1.3.2</version>
</dependency>

אם אתה ב-Java 8 או גרסה נמוכה יותר, אז אין צורך להוסיף את התלות למעלה.

Spring @PreDestroy

כאשר אנו מסמנים שיטת Spring Bean באימות PreDestroy, היא נקראת כאשר מופע ה-Bean נמחק מההקשר. זהו נקודה חשובה מאוד להבין – אם סוג ה־Spring Bean שלך הוא "prototype", אזי הוא לא ניהול מוחלט על ידי מכולת ה־Spring ושיטת PreDestroy לא תיקרא. אם קיימת שיטה בשם shutdown או close, אז מכולת ה־Spring תנסה להגדיר אותן באופן אוטומטי כשיטות קולאקטיביות כאשר ה־Bean נמחק.

Spring @PostConstruct ו־@PreDestroy דוגמה

הנה Bean של Spring פשוט עם @PostConstruct ו־@PreDestroy שיטות.

package com.journaldev.spring;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyBean {

	public MyBean() {
		System.out.println("MyBean instance created");
	}

	@PostConstruct
	private void init() {
		System.out.println("Verifying Resources");
	}

	@PreDestroy
	private void shutdown() {
		System.out.println("Shutdown All Resources");
	}

	public void close() {
		System.out.println("Closing All Resources");
	}
}

שים לב שגם הגדרתי שיטה בשם close כדי לבדוק אם היא נקראת כאשר ה־Bean שלנו נמחק או לא. הנה הקוד של קונפיגורציה פשוטה של Spring.

package com.journaldev.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MyConfiguration {
	
    @Bean
    @Scope(value="singleton")
    public MyBean myBean() {
	return new MyBean();
    }
	
}

I don’t need to explicitly specify my bean as a singleton but I will later change its value to “prototype” and see what happens with @PostConstruct and @PreDestroy methods. Here is my main class where I am creating spring context and getting few instances of MyBean.

package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MySpringApp {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();

		MyBean mb1 = ctx.getBean(MyBean.class);
		System.out.println(mb1.hashCode());

		MyBean mb2 = ctx.getBean(MyBean.class);
		System.out.println(mb2.hashCode());

		ctx.close();
	}

}

כאשר אנו מפעילים את הקלאס שנתנו למעלה, אנו מקבלים את הפלט הבא.

MyBean instance created
Verifying Resources
1640296160
1640296160
Shutdown All Resources
Closing All Resources

לכן, שיטת @PostConstruct נקראת לאחר התצורה של האובייקט. כאשר ההקשר נסגר, הוא קורא גם לשיטות shutdown ו־close.

Spring @PostConstruct ו־@PreDestroy עם טווח הפרוטוטייפ

פשוט שנה את ערך הטווח ל־prototype ב־MyConfiguration והפעל את המחלקה הראשית. תקבל פלט כמו בדוגמה למטה.

MyBean instance created
Verifying Resources
1640296160
MyBean instance created
Verifying Resources
1863374262

לכן ברור שמנגנון הקירום של Spring מאתחל את האובייקט בכל בקשה, קורא לשיטת ה־@PostConstruct שלו ואז מעביר אותו ללקוח. Spring אינו ניהול את האובייקט לאחר מכן, ובמקרה זה, הלקוח חייב לבצע את כל ניקוי המשאבים על ידי קריאה ישירה לשיטת PreDestroy.

סיכום

@PostConstruct ו־@PreDestroy הן איפוסי חיים חשובים לשימוש עם ניהול מחזור החיים של הפולס. אפשר להשתמש בהם כדי לוודא שהפולס נאתר באופן תקין ולסגור את כל המשאבים כאשר הפולס מוסר מההקשר של הקפיצית.

באפשרותך לבדוק את קוד הפרויקט המלא מה-מאגר ה-GitHub שלנו.

Source:
https://www.digitalocean.com/community/tutorials/spring-postconstruct-predestroy