1. 使用说明
通常我们项目中想要往spring容器中注入一个bean可以在项目初始化的时候结合@Bean注解实现。但是该方法适合项目初始化时候使用,如果后续想要继续注入对象则无可奈何。本文主要描述一种在后续往spring容器注入bean的方法。
2. 实现
2.1 说明
2.1.1 注册bean
- 定义BeanDefinition,注册类定义到factory中
- 创建对象,注册实例到fatory中
2.1.2 销毁bean
- 判断是否有类定义。有,则移除BeanDefinition
- 判断是否有对象。有,则从容器中去除
2.2 代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author pp_lan
* @date 2024/1/17
*/
@Component
public class SpringUtils {
@Auto

最低0.47元/天 解锁文章
1512

被折叠的 条评论
为什么被折叠?



