Spring @PostConstruct и пример @PreDestroy

Spring @PostConstruct и пример @PreDestroy

В Spring вы можете либо реализовать интерфейсInitializingBean and DisposableBean, либо указатьinit-method and destroy-method в файле конфигурации компонента для функции обратного вызова инициализации и уничтожения. В этой статье мы покажем вам, как использовать аннотации@PostConstruct и@PreDestroy, чтобы делать то же самое.

Note
Аннотации@PostConstruct и@PreDestroy не принадлежат Spring, они находятся в библиотеке J2ee - common-annotations.jar.

@PostConstruct и @PreDestroy

Компонент CustomerService с аннотацией @PostConstruct и @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");
    }

}

По умолчанию Spring не будет знать аннотации @PostConstruct и @PreDestroy. Чтобы включить его, вы должны либо зарегистрировать «CommonAnnotationBeanPostProcessor», либо указать «<context:annotation-config />» в файле конфигурации bean-компонента,

1. CommonAnnotationBeanPostProcessor



    

    
        
    

2.



    

    
        
    

Запустить его

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

Выход

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) вызывается после установки свойства сообщения, аcleanUp() method (@PreDestroy) вызывается после context.close ();

Скачать исходный код