Spring4.x中操作bean的初始化和销毁

在开发中,经常会在bean使用之前或者之后做些必要操作,下面提供两种方法:

1.java配置方式,使用@Bean的initMethod和destroyMethod(相当于xml配置的init-method和destroy-method)

2.注解方式,利用JSR-250的@PostConstruct和PreDestroy.

一:添加依赖

<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>jsr250-api</artifactId>
			<version>1.0</version>
		</dependency>

二:编写@Bean形式的Bean

public class BeanWayService {
	  public void init(){
	        System.out.println("@Bean-init-method");
	    }
	    public BeanWayService() {
	        super();
	        System.out.println("初始化构造函数-BeanWayService");
	    }
	    public void destroy(){
	        System.out.println("@Bean-destory-method");
	    }
}

三:编写JSR250形式的Bean

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

public class JSR250WayService {
	@PostConstruct //在构造函数执行完之后执行
    public void init(){
        System.out.println("jsr250-init-method");
    }
    public JSR250WayService() {
        super();
        System.out.println("初始化构造函数-JSR250WayService");
    }
    @PreDestroy //在bean销毁之前执行
    public void destroy(){
        System.out.println("jsr250-destory-method");
    }

}

四:配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.prepost")
public class PrePostConfig {
	
	@Bean(initMethod="init",destroyMethod="destroy") //initMethod指定bean构造之后执行
		// 和destroyMethod在bean销毁之前执行
	BeanWayService beanWayService(){
		return new BeanWayService();
	}
	
	@Bean
	JSR250WayService jsr250WayService(){
		return new JSR250WayService();
	}

}

五:测试

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(PrePostConfig.class);
		
		BeanWayService beanWayService = context.getBean(BeanWayService.class);
		JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);
		
		context.close();
	}

}

运行结果如下:


猜你喜欢

转载自blog.csdn.net/flysun3344/article/details/80375533