Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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/

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}