Injecting “foreign beans” into a new ApplicationContext

While moving towards full OSGi supported application I’ve started to restrict my application modules by Spring context to confine them almost as if they were OSGi modules. As we don’t have any static lookups anywhere this is practically OSGi without any package-imports and less class loader security; but we are getting there.

I need to give some services away to my modules and now, how do I do that? Quickly browsing through Pro Spring 2.5 and Spring Recipes and not finding anything I just started to look at GenericApplicationContext api after failing to access it’s BeanFactory before refreshing it.

There’s a method addBeanFactoryPostProcessor() which allows you to register beans into the newly initialized ConfigurableListableBeanFactory through various register* methods.

As in my case, the dependencies I needed to publish were autowired to my context building bean by it’s ApplicationContext and so adding them to any instantiated contexes was a breeze.

Another way to accomplish almost the same would be to simply set the parent ApplicationContext to the new ApplicationContexes but that would had allowed my modules to fetch other “non-specified” beans as well.

Not sure how ApplicationEvents would be propagated up if you set the parent application context, but as the GenericApplicationContext.addApplicationListener(..) methods documentation says that the new application listeners will only get events after the next refresh those might not get propagated in both directions; most likely only from childContext -> parentContext.

If you however choose to somehow specify what events can be and cannot be transferred between the contexes you might opt to add your custom ApplicationEventListener to propagate only the supported events.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: