Spring Custom Thread Scope Example

The Spring Custom Thread Scope Example show you how to create and implement a custom scope for for creating your own requirements. The need to create a Custom Scope actually depends on the problem at hand. To understand we will create a SimpleThreadScope. It implements the Scope interface which allows us to add, remove and specify a special callback method to manage scope lifecycle.

Creating a Custom Scope
One of the first things to consider when implementing a custom Scope class is how you will store and manage the scoped objects and destruction callbacks. In this Spring Custom Thread Scope Example we create a SimpleThreadScope so we store scoped objects in a Map of ThreadLocal instance. SimpleThreadScope has a short lived scope which we can manage and manually clear the scope using an additional clear() method.

Create Spring bean
We create a simple bean named Book for testing spring bean scope

Book.java

Configuring Custom Scope
First we create a bean definition of our custom scope bean and assign it with an id.

Next we registered our custom scope with the Spring IoC container using CustomScopeConfigurer and setting the scopes property and initialize it with a map containing a reference to our custom SimpleThreadScope bean together with a key. This key is used to register the custom scope.

Finally we configure the Book bean with our custom thread scope.

In short, we have the completed spring configuration file like below:

Demo Custom Scope
In this Spring Custom Thread Scope Example, we create the main class which test if the retrieved bean is the same as the subsequent.

Running the main above and output is printed like below

Spring Custom Thread Scope Example

As you see in the output, the instance of Book is created only when the instance does not exist in the SimpleThreadScope bean.

That’s all on the Spring Custom Thread Scope Example.

References
Spring Custom Scope Doc

Download complete source code, click link below

spring-custom-scope-example.zip (5 downloads)

If you found this useful, please share it with your friends

Leave a Comment

*

Please share it if you found this useful
Hide Buttons