Spring初始化Bean和销毁Bean的逻辑处理

如果需要Spring在Bean初始化或Bean销毁之后执行一些逻辑,那么有三种方法,

一、第一种方法是通过指定Bean的init-method方法和destroy-method的方法

1、首先先在Bean中添加两个方法,一个是在初始化后执行的方法,一个是在Bean销毁之后执行的方法

public class Bean {

    public void onInit() {
        System.out.println("Bean.onInit");
    }

    public void onDestroy() {
        System.out.println("Bean.onDestroy");
    }
}

2、在Spring的配置文件中为Bean的配置添加init-method和destroy-method属性,属性值就是Bean中定义的两个方法

       <bean class="com.model.Bean" init-method="onInit" destroy-method="onDestroy" id="bean"/>

3.测试

public class SpringTest {

    @Test
    public void test(){
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Bean bean = context.getBean("bean",Bean.class);
        System.out.println("bean"+bean);
        context.close();
    }
}

测试结果:

 

4、当然如果我们有很多的Bean需要指定init-method和destroy-method那么我们可以在Spring文件beans标签中添加

default-init-method和default-destroy-method以指定初始和销毁Bean后执行的方法,如果某些Bean中没有指定的方法,Spring 也不会报错

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
       default-init-method="onInit"
       default-destroy-method="onDestroy"
>

二、第二种方法是通过实现InitializingBean ,DisposableBean来实现在Bean初始化或Bean销毁之后执行一些逻辑

1、Bean实现InitializingBean ,DisposableBean的两个方法

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;


public class Bean implements InitializingBean ,DisposableBean {

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

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

2、测试结果

三、第三种方法是通过添加JAVA的@PostConstruct注解和@PreDestroy注解来自定义一些在spring bean初始化和销毁的时候触发的一些回调操作。

1、@PostConstruct注解在init-method方法上,@PreDestroy注解在destroy-method方法上

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Bean {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        System.out.println("Bean.afterPropertiesSet");
    }
    
    @PreDestroy
    public void destroy() throws Exception {
        System.out.println("Bean.destroy");
    }
    
}

2、如果注解不生效,请检查下Spring的注解扫描有没有扫描到Bean所在的包

    <context:component-scan base-package="com.model"/>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值