bean的作用域对生命周期的影响和后置处理器

bean的作用域对生命周期的影响和后置处理器

bean的作用域默认是单例的(singleton)

  • 若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时来执行
public class LifeCycleTest {
    @Test
    public void test(){
        //ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
    }
}

bean的作用域是多例时(prototype)

  • 若bean的作用域为多例时,生命周期的前三个步骤会在获取bean对象时来执行,但销毁的方法不再由IOC容器来管理

public class LifeCycleTest {
    @Test
    public void test(){
        //ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
    }
}

public class LifeCycleTest {
    @Test
    public void test(){
        //ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }
}

bean的后置处理器

  • bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行

创建bean的后置处理器:

public class MyBeanPostProcessor implements BeanPostProcessor {


    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //此方法再bean的生命周期初始化之前执行
        System.out.println("MyBeanPostProcessor-->后置处理器的postProcessBeforeInitialization");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //此方法再bean的生命周期初始化之后执行
        System.out.println("MyBeanPostProcessor-->后置处理器的postProcessAfterInitialization");
        return bean;
    }
}

测试

public class LifeCycleTest {
    @Test
    public void test(){
        //ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值