如何在从文件加载之前将bean注入ApplicationContext?

我有一个FileSystemXmlApplicationContext ,我希望XML中定义的bean将构造函数参数作为一个未在Spring中声明的bean

例如,我想这样做:

    

所以我可以想象这样做:

 Object myBean = ... context = new FileSystemXmlApplicationContext(xmlFile); context.addBean("myBean", myBean); //add myBean before processing context.refresh(); 

除了没有这样的方法:-(有谁知道我怎么能做到这一点?

如何以编程方式创建一个空的父上下文,使用getBeanFactory返回SingletonBeanRegistry实现的事实将对象注册为具有该上下文的BeanFactorySingletonBeanRegistry

 parentContext = new ClassPathXmlApplicationContext(); parentContext.refresh(); //THIS IS REQUIRED parentContext.getBeanFactory().registerSingleton("myBean", myBean) 

然后将此上下文指定为“真实”上下文的父级。子上下文中的bean将能够引用父级中的bean。

 String[] fs = new String[] { "/path/to/myfile.xml" } appContext = new FileSystemXmlApplicationContext(fs, parentContext); 

由于我使用AnnotationConfigApplicationContext解决了这个问题,我找到了以下替代方案:

 DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerSingleton("customBean", new CustomBean()); context = new AnnotationConfigApplicationContext(beanFactory); context.register(ContextConfiguration.class); context.refresh();