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

 

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值