Spring框架中注解@PostConastruct 和 @PreDestroy来实现Bean初始化和销毁时候执行方法

Spring框架中注解@PostConastruct 和 @PreDestroy来实现Bean初始化和销毁时候执行方法

引言

Spring框架中在bean初始化和销毁时候执行某个方法的三种实现方式。

  1. Spring框架中通过注解@PostConastruct@PreDestroy来实现Bean初始化执行和销毁时候执行方法;
  2. Spring框架中通过实现接口InitializingBean ,DisposableBean来实现Bean初始化执行和销毁时候执行方法;
  3. Spring框架中通过xml配置文件中bean的init-method="" destroy-method=""来实现Bean初始化执行和销毁时候执行方法;

一.Spring框架中通过注解@PostConastruct@PreDestroy来实现Bean初始化执行和销毁时候执行方法;

通过注解的方式推荐使用,后期spring boot也基本使用注解来配置,举个栗子:

package com.note234.service;

import javax.annotation.PostConstruct;

public class TestService {

	@PostConstruct
	public void init(){
		System.out.println("Bean 开始初始化啦。。");
	}
	
	public void dostory(){
		System.out.println("Bean 销毁了。。。");
	}
}

二.Spring框架中通过实现接口InitializingBean ,DisposableBean来实现Bean初始化执行和销毁时候执行方法;

举个栗子:

package com.note234.service;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class TestService implements InitializingBean,DisposableBean{


	@Override
	public void destroy() throws Exception {
		System.out.println("Bean 销毁了。。。");
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("Bean 开始初始化啦。。");
		
	}
}

三.Spring框架中通过xml配置文件中bean的init-method="" destroy-method=""来实现Bean初始化执行和销毁时候执行方法;

举个例子:

<bean id="testService" class="com.note234.service.TestService" init-method="init" destroy-method="destroy"></bean>

 

Spring框架中注解@PostConastruct 和 @PreDestroy来实现Bean初始化和销毁时候执行方法

相关文章:

你感兴趣的文章:

标签云: