finalize()并不是必须要执行的,它只能执行一次或者0次。
Spring Bean垃圾回收肯定是在关闭Spring上下文之后.
Rumenz.java
package com.rumenz; public class Rumenz { public void print(){ System.out.println("......."); } //覆盖finalize方法 @Override public void finalize() throws Throwable { System.out.println("Rumenz对象被回收"); } }DemoApplication.java
package com.rumenz; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; public class DemoApplication { public static void main(String[] args) throws InterruptedException { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); ac.register(DemoApplication.class); //启动Spring上下文 ac.refresh(); //关闭Spring上下文 ac.close(); System.out.println("Spring上下文已关闭"); Thread.sleep(5000L); //强制进行GC是为了观察回收过程 System.gc(); Thread.sleep(5000L); } @Bean("rumenzz") public static Rumenz rumenz(){ Rumenz rumenz = new Rumenz(); return rumenz; } }输出
Spring上下文已关闭 Rumenz对象被回收由于finalize不是每次一定会被调用,如果没有结果需要多运行几次.
原文: https://rumenz.com/rumenbiji/Spring-Bean-GC.html