user2595169
user2595169

Reputation: 145

How to refer a Spring bean at run time in a different context

All,

I have a applicationContext and the beans in them are initialized at my application start up - I will call this parent context.

I have another applicationContext (secondary) - this is deployed into my application at run time - the beans in them are manually read and loaded into my parent context, I do this loading all the beans upfront and then register them as singletons to my parent context - a snippet is shown below. This works as expected.

ApplicationContext fileContext = new     FileSystemXmlApplicationContext("file:" + fileList.get(i).getPath());
Map<String, List> beansOfType = fileContext.getBeansOfType(List.class, false, false);
String[] beanNames = fileContext.getBeanDefinitionNames();
ConfigurableApplicationContext parentConfContext = (ConfigurableApplicationContext)parentContext;
BeanDefinitionRegistry beanReg = (BeanDefinitionRegistry)parentConfContext.getAutowireCapableBeanFactory();
for (String string : beanNames) {
try {
    beanReg.removeBeanDefinition(string);
} 
catch (NoSuchBeanDefinitionException e) {
// TODO Auto-generated catch block
}
parentConfContext.getBeanFactory().registerSingleton(string,     fileContext.getBean(string));
}

Now I want to refer a bean in my parent context in my secondary application context (I am passing a bean in parent context as a property reference in my secondary context) - but when I do this I get a 'No bean named' exception. which is obvious because the secondary context has no idea of the parent context.

I have tried setting lazy-init="true" to the bean in secondary context - but this does not help - can some one suggest on how to over come this?

regards D

Upvotes: 3

Views: 1347

Answers (2)

Artem Bilan
Artem Bilan

Reputation: 121212

If you refer some parent bean from the child context, you have to just say that child context something about your parent:

ConfigurableApplicationContext parentConfContext = (ConfigurableApplicationContext)parentContext;

ApplicationContext fileContext = 
    new FileSystemXmlApplicationContext(new String[] {"file:" + fileList.get(i).getPath()}, 
                           parentConfContext);

Upvotes: 1

reos
reos

Reputation: 8324

In Spring the context are independent. If you want to load a bean in two contexts you need a common configuration file/class.

For example, you have a file/class A, for the first context and a file/class B for the second context. Then if you have a bean that need to be in A and B contexts you need a third file/class C with that bean definition. Finally you need import the file/class C into the A and B.

https://spring.io/understanding/application-context

Upvotes: 0

Related Questions