Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Controller init method

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.

like image 283
onigunn Avatar asked Jul 13 '10 12:07

onigunn


1 Answers

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 @PostConstruct. 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.

like image 129
Nils Schmidt Avatar answered Sep 24 '22 01:09

Nils Schmidt