RESTEasy – Share Context Data with ResteasyProviderFactory

Many times we get into situation where we have to pass data from-to multiple layers in our application. An example can be application using interceptors. Suppose we have two interceptors in our application, one for login check and second for putting audit information in database. We want to use the User object from first interceptor, into second interceptor.

In RESTEasy based applications, above functionality can be easily implemented using ResteasyProviderFactory instance. ResteasyProviderFactory is enabled by adding a filter in web.xml file using below definition:


Now you can easily get the instance of ResteasyProviderFactory in any class in scope of RESTEasy context. So, to share data between interceptors, you will need to do two steps:

1)Set the data in context map

This context data is set using pushContext() method. This method add the data to a thread local stack defined as:

protected static ThreadLocalStack<Map<Class<?>, Object>> contextualData 
						= new ThreadLocalStack<Map<Class<?>, Object>>();

You need to push data as follows:

User user = new User();
//Set some user attributes

//Get registered ResteasyProviderFactory instance
ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();

//Add user into context data map
factory.pushContext(User.class, user);

2)Get the data from context map

Getting back the data set in first step is very simple. Use popContextData() method. This context data is thread-local in nature so you do not need to worry about getting wrong data when retrieving in another place in your code.

 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();

This way you can use ResteasyProviderFactory to share data between multiple layers in your application.

Happy Learning !!

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial