spring创建对象和销毁对象

        调用初始化方法很容易,只要在xml文件中声明配置init-method属性,然后将方法名注入到里面即可,问题出在销毁方法用了很多方法都不能调用。

        网上有很多方法回收销毁对象,比如将对象赋值为null,利用System.gc()方法强制回收等等。。

         解决方案:将测试类中声明的ApplicationContext对象换成AbstractApplicationContext对象, 配置destroy-method,将自己声明的方法注入到里面,然后调用registerShutdownHook方法即可调用对象的销毁方法。

        若还是无法调用destroy方法,则将配置文件中scope="prototype"改为scope="prototype"。

实体类

package com.LL.sp1;

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

@Data
public class HelloWord {
    private String message;

    public void init(){
        System.out.println("init方法初始化");
    }


    public void afterPropertiesSet() throws Exception {
        System.out.println("HelloWorld初始化了!");
    }

    public void destroy(){
        System.out.println("destroy方法销毁");
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("调用了finalize方法");
    }
}

Beans.xml

 <bean id="helloWorld" class="com.LL.sp1.HelloWord" scope="singleton" init-method="init" destroy-method="destroy">
        <property name="message" value="Hello World!" />
    </bean>

 Test

   public static void main(String[] args) {
        AbstractApplicationContext context =
                new ClassPathXmlApplicationContext("Bean.xml");
        HelloWord he = (HelloWord) context.getBean("helloWorld");
        System.out.println("获得的信息"+he.getMessage());
        context.registerShutdownHook();

    }

补充:可以在xml配置文件中声明如下方法,即可为所有bean的initdestroy方法进行赋值。

default-init-method="init" 
default-destroy-method="destroy">

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狗头实习生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值