The Holy Java

Building the right thing, building it right, fast

Spring: Make an Externally Created Object Available to Beans in applicationContext.xml

Posted by Jakub Holý on October 11, 2011

If your Spring beans need access to an object that is not created by Spring itself, you can “inject” it into the context by using a static parent context and registering the object with it. Beans can then reference it just as if it was defined in the application context file.

Java: Configure ApplicationContext with an Injected Bean

import org.springframework.context.ApplicationContext;

Object externalyDefinedBean = ...;
GenericApplicationContext parentContext = new StaticApplicationContext();
parentContext.getBeanFactory().registerSingleton("injectedBean", externalyDefinedBean);
parentContext.refresh();   // seems to be required sometimes

ApplicationContext context = new FileSystemXmlApplicationContext(springConfigs, parentContext);

Xml: Make Use of It

<bean id="springBean" class="your.SpringBeanType">
   <!-- Note: The injectedBean is defined outside of Spring config -->
   <property name="someProperty" ref="injectedBean" />



2 Responses to “Spring: Make an Externally Created Object Available to Beans in applicationContext.xml”

  1. Oleksandr said

    Thank you!

Sorry, the comment form is closed at this time.

%d bloggers like this: