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就会发生错误:
猜你喜欢
spring/springmvc
1259
创建一个MarkControllerMarkController类上有@RestController注解importorg.springframework.web.bind.annotation.RestController;/***@ClassNameMarkController*@Description:TODO*@AuthorJiajiajia*@VersionV1.0**/@RestCon
jenkins,软件使用
171
-Git一、新建任务填写任务名字,选择Freestyleproject点击确定二、General配置在General配置中,填写任务描述。可以点击高级,选中“使用自定义的工作空间”选项,配置任务的工作目录
java项目
712
springboot+mybatis配置多数据源并利用aop实现自动切换(demo)
java基础,springboot
234
。
二、配置springboot服务 要将程序注册成服务,必须保证jar有执行(下面例子中的x)的权限,否则服务无法启动。
SystemVInit服务 SystemVInit服务都在目录/etc
weblog
1364
配置类importjavax.servlet.ServletContext;importjavax.servlet.annotation.WebListener
框架
807
springboot+mybatis配置多数据源并利用aop实现自动切换1.项目大致结构2.pom依赖dependencygroupIdorg.springframework.boot
official
151
BeanPostProcessor是SpringIOC容器给我们提供的一个扩展接口。,他的作用主要是如果我们需要在Spring容器完成Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处
ofc
什么是Bean生命周期?
official
122
Bean生命周期描述的是Spring中一个Bean创建过程和销毁过程中所经历的步骤,其中Bean创建过程是重点。程序员可以利用Bean生命周期机制对Bean进行自定义加工。
最近发表
归档
2018年11月
12
2018年12月
33
2019年01月
28
2019年02月
28
2019年03月
32
2019年04月
27
2019年05月
33
2019年06月
6
2019年07月
12
2019年08月
12
2019年09月
21
2019年10月
8
2019年11月
15
2019年12月
25
2020年01月
9
2020年02月
5
2020年03月
16
2020年04月
4
2020年06月
1
2020年07月
7
2020年08月
13
2020年09月
9
2020年10月
5
2020年12月
3
2021年01月
1
2021年02月
5
2021年03月
7
2021年04月
4
2021年05月
4
2021年06月
1
2021年07月
7
2021年08月
2
2021年09月
8
2021年10月
9
2021年11月
16
2021年12月
14
2022年01月
7
2022年05月
1
标签
算法基础
linux
前端
c++
数据结构
框架
数据库
计算机基础
储备知识
java基础
ASM
其他
深入理解java虚拟机
nginx
git
消息中间件
搜索
maven
redis
docker
dubbo
vue
导入导出
软件使用
idea插件
协议
无聊的知识
jenkins
springboot
mqtt协议
keepalived
目录
祝愿神州十三飞行乘组平安归来