【SpringBoot基础】Bean的初始化与注销 注解实现

【SpringBoot基础】Bean的初始化与注销 注解实现

内容概要

Spring 对 bean的生命周期操作,提供支持。

环境jar包

	jdk: jdk1.8.0_121(32位)
	pom:
	    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.10.RELEASE</version>
        </dependency>

文件结构

在这里插入图片描述

实例 DemoBean

 package BeanIsLife;

public class DemoBean {
   //预置初始化
   public void  init(){
       System.out.println("DemoBean  is  inited!");
   }
   //预置注销
   public void destroy() {
       System.out.println("DemoBean is destroied!");
   }
   //构造器
   public DemoBean(){
       super();
       System.out.println("DemoBean 构造成功!");
   }
   //调用
   public void say(){
       System.out.println("DemoBean 调用!");
   }
}

配置类 BeanConfig

package BeanIsLife;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("BeanIsLife")
public class BeanConfig {
	//将返回值 最为bean 为其设置 初始、注销方法
    @Bean(initMethod ="init",destroyMethod ="destroy")
    public DemoBean getBean(){
        return new DemoBean();
    }
}

测试类Main

 package BeanIsLife;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String []args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
        //先构造 获取内存 再初始化 
        DemoBean bean = context.getBean(DemoBean.class);
        //调用
        bean.say();
        //容器关闭  调用注销方法 
        context.close();

    }
}

输出结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Shane_FZ_C/article/details/89021371