Рубрики
Без рубрики

Пример весны @PostConstruct и @PreDestroy

– Весна @Постконструкция и @Предопределение пример

Весной вы можете либо реализовать интерфейс InitializingBean и DisposableBean , либо указать метод инициализации и метод уничтожения в файле конфигурации компонента для функции обратного вызова инициализации и уничтожения. В этой статье мы покажем вам, как использовать аннотации @Постконструкция и @Предопределение чтобы сделать то же самое.

@Постконструкция и @Предопределение

Компонент обслуживания клиентов с аннотацией @PostConstruct и @PreDestroy

package com.mkyong.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 “, либо указать ” <контекст:аннотация-конфигурация/> ” в файле конфигурации компонента,

1. Процессор CommonAnnotationBeanPostПроцессор



	

	
		
	
		

2. <контекст: аннотация-конфигурация/>



	

	
		
	
		

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

package com.mkyong.common;

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

import com.mkyong.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.mkyong.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

Метод init() (@PostConstruct) вызывается после установки свойства сообщения, а метод Cleanup() (@PreDestroy) вызывается после context.close();

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

Оригинал: “https://mkyong.com/spring/spring-postconstruct-and-predestroy-example/”