Local singletons in Spring

When developing applications using dependency injection containers there are times when having a single global scope is not enough. As an example, consider having multiple instances of some “heavy” component. Creating such components requires dependencies declared as singletons within the scope of a particular object hierarchy (usually rooted in the component itself), and as prototypes in a global context. Sort of local singletons or rather scoped singletons.

Imagine a document editor that allows to edit multiple documents. The editor component is presumably expensive to create and hard to share. In this case, we create multiple editor instances and switch between them. Besides using globally shared dependencies defined on the application level, each instance uses its own local set of dependencies which it shares between all its sub-components.

If you use Spring, you can solve this puzzle by using the child context. The idea is to create a separate java config for component’s dependencies with enabled component scanning and to place it into a dedicated package.

First, we define the classes related to the editor component: the editor’s class itself, its dependencies (the selection manager class in our case) and the editor’s java config. We place them into a dedicated package (along with the rest of the editor’s code):

Next we define the editor’s factory class along with its implementation. We put it to the main application package:

In the main application context we import the editor’s config:

The main application context (parent context) knows only about its dependencies including the editor factory. The factory creates the child context using both provided editor’s configuration and the parent context. Singletones created by the factory only exist in the child context and shared there. Singletons declared in the parent context are available to the child context as well.

Share on FacebookShare on LinkedInShare on Google+Tweet about this on TwitterPin on PinterestShare on RedditDigg this

Vitaly Tsaplin

Hey, I am Vitaly and this is my blog. I live in Basel and work at Adobe.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Leave a Comment

Time limit is exhausted. Please reload CAPTCHA.