Vish
Vish

Reputation: 879

Singleton Object Created for each Request

I want to create a singleton object whose scope is basically only the request. This will be used to collect the errors and we need to send error whenever we send the response back.

Can anyone provide pointers toward this thing? I am also using spring.

I tried using Spring container singleton object scope session or request but still my object is holding values from the earlier request

I am using this error object with AspectJ. Will that may cause problem on static binding?

Upvotes: 1

Views: 2781

Answers (4)

eaglestorm
eaglestorm

Reputation: 1202

If you set the Object life cycle in the Spring container to be per request then it should only exist for that HttpRequest.

Generally for direct injection containers like Spring when you set the object life cycle or object scope to be per request then it should create an new instance of the object for each http request that it recieves.

If it is not doing this then I would assume that it is more than likely something to do with your configuration.

Singleton is the defualt for the spring container when creating beans I think so you have to specifically set the object scope to per request.

Bean Scopes http://static.springsource.org/spring/docs/2.5.x/reference/beans.html

Upvotes: 1

Amareswar
Amareswar

Reputation: 2064

You can use ThreadLocal.

Upvotes: -1

DaveH
DaveH

Reputation: 7335

I'm not sure that singleton is what you want here - if two requests arrived concurrently they would share the singleton object, and their errors will get mixed up.

Is it possible to create an object to hold the errors and put that in to a ThreadLocal object. The scope of the object will be constrained by the request, and access to it in the ThreadLocal object is easily achieved from within your application without having to pass a refernce to the object around.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240948

how about

//sync this code
if(request.getAttribute("someKey") == null){
     // create object and set it
}

Upvotes: 1

Related Questions