views:

73

answers:

2

Hi there,

as far as I understand are spring controllers stateless right? If I set a field to a value, this is revoked by the next call.

Is there a possibility to add a init-method or something? A method which is called once, when my controller is triggerd? I'm using spring 3.0 and a annotation configuration atm.

+5  A: 

Spring Controllers should be handled stateless by default, that is correct. Nevertheless this does not mean your value will be revoked by the next call. From the programmers perspective it is not decidable if you end up with same instance of your controller or a different instance. It is further more not assured that no one else used the controller (and therefore changed its state in the meantime). This is why it is not advisable to save any state at all in fields of your controller. Maybe you should reconsider the need for a field in your controller.

In fact there is a init method for spring beans. You can simply annotate a public void method on your controller with @InitMethod. This method is executed after dependencies have been injected. Thus, this method is invoked exactly ones after the controller instance is created.

As far as I understand your question you look for some method that is executed before every call to a method of your controller. In that case you could simply at a call to your "init"-method in the beginning of each of your controller methods. If you dont want to do this explicit in your code AOP provide you an alternative.

Nils Schmidt
+2  A: 

As far as I understand are spring controllers stateless right? If I set a field to a value, this is revoked by the next call.

I believe that is incorrect: Spring controllers can be stateful. You should be very careful though because a Controller is expected to be re-entrant and thread-safe and to support multiple threads simultaneously executing multiple requests.

It is probably safe to say that it best practice for a controller to be designed to be effectively stateless; i.e. no state that changes while the controller is "live".

Is there a possibility to add a init-method or something?

It is not entirely clear what you mean. However:

  • The controller's handleRequest is called to start a request.
  • If you declare any bean (e.g. a controller bean) as ApplicationContextAware it will be called back to inform it of the ApplicationContext.
  • If you declare any bean as ServletContextAware it will be called back to inform it of the ServletContext.
  • If you declare any bean as an InitializingBean it will be called back when all properties have been set.

And there are doubtless other callbacks and hooks that you could use to trigger some delayed initialization / context setting.

(I'm not sure how these callbacks / hooks map to annotations ... but I'm sure that they do.)

Stephen C