spring的配置bean完成任务后如何自动销毁【springboot】
有时项目在初始化是会有一些配置类(bean) 加入ioc容器,在项目加载完成后该bean就没有用了,可以从ioc容器中销毁。具体如下:
bean
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Test implements CommandLineRunner,DisposableBean {
@Autowired
private ApplicationContext context; //注入ApplicationContext
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
// do
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory)context.getAutowireCapableBeanFactory();
Test t=(Test) defaultListableBeanFactory.getBean("test");//获取并打印
System.err.println(t);
defaultListableBeanFactory.removeBeanDefinition("test");//销毁自己
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.err.println("销毁");
}
}
这样项目在启动的时候会执行run方法,执行完run方法后即可销毁自身
启动时打印:
销毁后如果再次获取bean就会发生错误:
fixed
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。