views:

169

answers:

1

Is there a nice way to have Spring's @Controller classes to call a specific method once per request?

Right now I'm using a method annotated with @InitBinder for this purpose, but this is suboptimal as @InitBinder methods get called several times per request. I just want to do some initialization / update stuff to use in my controllers.

What I'm looking for is something like Rails' before_filter, but as far as I can tell there's no functionality like that in Spring.

+1  A: 

Sounds like you need a request-scoped controller bean. Spring will create a new instance of the controller for each request, and will initialize the bean each time using the standard mechanisms like @PostConstruct.

skaffman
I already thought about such a solution, but I don't want to initialize my controllers on each request. I just want to do some small cleanup tasks (e.g. resetting some properties used inside my views). So this would be possible, but I hoped for a more clean solution.
Koraktor
Spring controllers are by default shared between threads and requests. If you have per-request state in your controller beans, then you should not share them between requests, and request-scoped beans are the cleanest and safest way to handle this.
skaffman
Is there a way to autowire a request-scoped bean into a singleton-scoped controller?
Koraktor
Yes: http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes-other-injection
skaffman