Spring @PostConstruct und @PreDestroy Beispiel

Beispiel für Spring @PostConstruct und @PreDestroy

In Spring können Sie entweder dieInitializingBean and DisposableBean-Schnittstelle implementieren oder dieinit-method and destroy-method in der Bean-Konfigurationsdatei für die Initialisierungs- und Zerstörungs-Rückruffunktion angeben. In diesem Artikel zeigen wir Ihnen, wie Sie mit Annotation@PostConstruct und@PreDestroy dasselbe tun.

Note
Die Annotationen@PostConstruct und@PreDestroygehören nicht zu Spring, sondern befinden sich in der J2ee-Bibliothek - common-annotations.jar.

@PostConstruct und @PreDestroy

Eine CustomerService-Bean mit der Annotation @PostConstruct und @PreDestroy

package com.example.customer.services;

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

public class CustomerService
{
    String message;

    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }

    @PostConstruct
    public void initIt() throws Exception {
      System.out.println("Init method after properties are set : " + message);
    }

    @PreDestroy
    public void cleanUp() throws Exception {
      System.out.println("Spring Container is destroy! Customer clean up");
    }

}

Standardmäßig erkennt Spring die Annotation @PostConstruct und @PreDestroy nicht. Um es zu aktivieren, müssen Sie entweder "CommonAnnotationBeanPostProcessor" registrieren oder "<context:annotation-config />" in der Bean-Konfigurationsdatei angeben.

1. CommonAnnotationBeanPostProcessor



    

    
        
    

2.



    

    
        
    

Starte es

package com.example.common;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.customer.services.CustomerService;

public class App
{
    public static void main( String[] args )
    {
        ConfigurableApplicationContext context =
          new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");

        System.out.println(cust);

        context.close();
    }
}

Ausgabe

Init method after properties are set : im property message
com.example.customer.services.CustomerService@47393f
...
INFO: Destroying singletons in org.springframework.beans.factory.
support.DefaultListableBeanFactory@77158a:
defining beans [customerService]; root of factory hierarchy
Spring Container is destroy! Customer clean up

initIt() method (@PostConstruct) wird aufgerufen, nachdem die Nachrichteneigenschaft festgelegt wurde, undcleanUp() method (@PreDestroy) wird nach context.close () aufgerufen.

Quellcode herunterladen