spring bean 手动管理:https://www.yht7.com/news/99552
/** 方法二:AnnotationConfigApplicationContext(Bootstrap.class) **/
AnnotationConfigApplicationContext applicationContext1 = new AnnotationConfigApplicationContext(Bootstrap.class);
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext1.getBeanFactory();
beanFactory.registerSingleton("test",new Test());
第四种:继承ApplicationContextAware
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
public class SpringContextUtils implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
/** 方法一:继承ApplicationContextAware:获得applicationContext **/
// 将applicationContext转换为ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
// 获取bean工厂并转换为DefaultListableBeanFactory
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
//defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinition);
}
}