Jakub is a Java EE developer since 2005 and occasionally a project manager, working currently with Iterate AS. He's highly interested in developer productivity (and tools like Maven and AOP/AspectJ), web frameworks, Java portals, testing and performance and works a lot with IBM technologies. A native to Czech Republic, he lives now in Oslo, Norway. Jakub is a DZone MVB and is not an employee of DZone and has posted 155 posts at DZone. You can read more from them at their website. View Full User Profile

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

10.12.2011
| 7105 views |
  • submit to reddit

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;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.StaticApplicationContext;

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" />
</bean>

 Viola!

 

From http://theholyjava.wordpress.com/2011/10/11/spring-make-an-externally-created-object-available-to-beans-in-applicationcontext-xml/

Published at DZone with permission of Jakub Holý, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Ragnar Westad replied on Thu, 2011/10/13 - 5:56am

Well done sir, and what an excellent timing! I was just sitting here wondering how I could avoid creating the mandatory "service" property for my JmsInvokerServiceExporter in the same Spring config, but rather do it in the test since it is a mocked service. Then decided to take a break and read some IT related news... And your solution was a perfect fit. Thanks! :-)

Jakub Holý replied on Mon, 2011/10/17 - 3:20am

You're most welcome, Ragnar!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.