Spring @PostConstruct et @PreDestroy, exemple

Exemple Spring @PostConstruct et @PreDestroy

Dans Spring, vous pouvez soit implémenter l'interfaceInitializingBean and DisposableBean, soit spécifier lesinit-method and destroy-method dans le fichier de configuration du bean pour la fonction de rappel d'initialisation et de destruction. Dans cet article, nous vous montrons comment utiliser les annotations@PostConstruct et@PreDestroy pour faire la même chose.

Note
Les annotations@PostConstruct et@PreDestroy n'appartiennent pas à Spring, elles se trouvent dans la bibliothèque J2ee - common-annotations.jar.

@PostConstruct et @PreDestroy

Un bean CustomerService avec annotation @PostConstruct et @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");
    }

}

Par défaut, Spring ne connaîtra pas l'annotation @PostConstruct et @PreDestroy. Pour l’activer, vous devez soit enregistrer ‘CommonAnnotationBeanPostProcessor’ ou spécifier le ‘<context:annotation-config />’ dans le fichier de configuration du bean,

1. CommonAnnotationBeanPostProcessor



    

    
        
    

2.



    

    
        
    

Exécuter

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();
    }
}

Sortie

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

LeinitIt() method (@PostConstruct) est appelé, après la définition de la propriété de message, et lecleanUp() method (@PreDestroy) est appelé après le context.close ();

Télécharger le code source