I have a FileSystemXmlApplicationContext
and I would like the beans defined in the XML to take as a constructor argument a bean which is not declared in Spring
If the existing context needs the bean you wish to inject then things need to be done a little differently. The approaches in other answers don't work for the following reasons
This can be worked around by using a "bean factory post processor", this allows code to be run after the context is loaded but before it it refreshed.
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
applicationContext.setConfigLocation("/org/example/app-context.xml");
applicationContext.getBeanFactoryPostProcessors().add(new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerSingleton("customBeanName", customBean);
}
});
applicationContext.refresh();