spring boot: Bean的初始化和销毁 (一般注入说明(三) AnnotationConfigApplicationContext容器 JSR250注解)

时间:2022-09-18 19:41:16

 

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

使用AnnotationConfigApplicationContext可以实现基于Java的配置类加载Spring的应用上下文.避免使用application.xml进行配置。在使用spring框架进行服务端开发时,个人感觉注解配置在便捷性,和操作上都优于是使用XML进行配置;

 

使用JSR250注解需要在maven的pom.xml里面配置

<!-- 增加JSR250支持 -->
    <dependency>
    	<groupId>javax.annotation</groupId>
    	<artifactId>jsr250-api</artifactId>
    	<version>1.0</version>
    </dependency>

  

 

 

prepostconfig文件:

package ch2.prepost;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


//声明这是一个配置类
@Configuration
//自动扫描ch2.prepost包下的@Service,@Component,@Repository,@Contrller注册为Bean
@ComponentScan()
public class PrePostConfig {

	
	//initMethod,destoryMethod制定BeanWayService类的init和destory在构造方法之后、Bean销毁之前执行
	@Bean(initMethod="init",destroyMethod="destory")
	BeanWayService beanWayService()
	{
		return new BeanWayService();
	}
	
	//这是一个bean
	@Bean
	JSR250WayService jsr250WayService(){
		return new JSR250WayService();
	}
	
}

  

JSR250WayService文件

package ch2.prepost;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


public class JSR250WayService {

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

  

BeanWayService文件

package ch2.prepost;

//使用@bean的形式bean
public class BeanWayService {

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

  

运行Main文件:

package ch2.prepost;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

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

  

 

运行结果:

初始化构造函数JSR250WayService
jsr250-init-method

jsr250-destory-method


初始化构造函数-method

@Bean-init-method

@Bean-destory-method