spring 中bean生命周期

本文深入探讨了Spring框架中Bean的生命周期管理,通过实现特定接口来展示Bean从创建到销毁的全过程。介绍了如何利用Spring的Bean生命周期特性进行初始化和清理操作。

从头开始学习spring(一)

传统编程中,依赖关系比较多的情况下,导致维护成本直线上升,spring 采用Ioc对bean进行管理,减少了开发人员的工作量

正确理解spring bean 的生命周期非常重要

package com.study.spring.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


public class MyBeanLifeCycle implements BeanNameAware, BeanFactoryAware,
    ApplicationContextAware, BeanPostProcessor, InitializingBean, DisposableBean {

    @Override
    public void setBeanName(String s) {
        System.out.println("bean id : " + s);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("destroy");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("beanFactory : " + beanFactory.toString());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("applicationContext : " + applicationContext.getApplicationName());
    }

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("postProcessBeforeInitialization : " + s);
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("postProcessAfterInitialization : " + s);
        return o;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet");
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd">


  <bean class="com.study.spring.service.impl.HelloServiceImpl" id="helloService"/>

  <bean id="myBean" class="com.study.spring.beans.MyBeanLifeCycle"/>

</beans>

  

 

转载于:https://www.cnblogs.com/liuzyw/p/7594651.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值