Spring:Bean的生命周期

Bean的生命周期分为五大部分

1.实例化Bean,为Bean分配空间

2.Bean的装配和注入

3.Bean的初始化

  • 实现Aware通知的方法,如ApplicationContextAware等
  • 执行BeanProcessor初始化前置方法
  • 执行PostConstruct方法
  • 执行自己指定的init-method 方法
  • 执行BeanProcessor初始化后置方法

4.使用Bean

5.销毁Bean

销毁容器的各种⽅法,如 @PreDestroy方法等


实例代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
   <!--配置存储 Bean 对象的扫描根路径-->
   <content:component-scan base-package="com.rhaegal"></content:component-scan>

   <!--注入beanlife对象到Spring容器中-->
   <bean name = "beanlife" class="com.rhaegal.controler.BeanLifeComponent" init-method="initMethod"></bean>
</beans>
public class BeanLifeComponent implements BeanNameAware {

    @Override
    public void setBeanName(String s) {
        System.out.println("执行了 BeanName 通知:" + s);
    }

    //这里的方法名任意
    public void initMethod(){
        System.out.println("执行了 initMethod 方法");
    }

    //这里的方法名任意
    @PostConstruct
    public void myPostConstruct(){
        System.out.println("执行了 PostConstruct 方法");
    }

    //这里的方法名任意
    @PreDestroy
    public void myPreDestroy(){
        System.out.println("执行力 PreDestroy 方法");
    }

    public void use(){
        System.out.println("执行了 use 方法");
    }
}
public class App {
    public static void main(String[] args) {
        //Bean的生命周期
        ClassPathXmlApplicationContext context =
             new ClassPathXmlApplicationContext("spring-config.xml");
        BeanLifeComponent component =
                context.getBean("beanlife",BeanLifeComponent.class);
        component.use();
        //关闭容器
        context.destroy();
      }
}

执行结果如下:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值