调用初始化方法很容易,只要在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的init和destroy方法进行赋值。
default-init-method="init"
default-destroy-method="destroy">