Spring Controller Initialization Method

As far as I understand, spring controllers are entitled to the absence of stateless people? If I set the field to, this will be undone by the next call.

Is it possible to add an init method or something else? A method that is called once when my controller starts? I am using spring 3.0 and atm annotation configuration.

+4
source share
2 answers

Spring By default, controllers should be handled by default, this is true. However, this does not mean that your value will be canceled on the next call. From the point of view of programmers, this is not permissible if in the end you get the same instance of your controller or another instance. In addition, I’m no longer sure that no one else used the controller (and therefore changed its state in the meantime). This is why it is not recommended to save any state at all in the fields of your controller. Perhaps you should reconsider the need for a field in your controller.

Actually there is an init method for spring beans. You can simply annotate the public void method on your controller with @PostConstruct . This method is executed after the dependencies are entered . Thus, this method is called exactly after creating the controller instance.

As far as I understand your question, you are looking for some method that is executed before each method call of your controller. In this case, you can simply call your init method at the beginning of each of your controller methods . If you do not want to make this explicit in your AOP code, you can choose an alternative.

+19
source

As far as I understand, spring controllers are entitled to the absence of stateless people? If I set the field to, this will be undone by the next call.

I believe this is not true: spring controllers may be functional. You have to be very careful because it is expected that the controller will be reconnected and thread safe and will support multiple threads at the same time, by executing multiple requests.

It is probably safe to say that best practices for the controller must be effective in order to be stateless; that is, there is no state that changes when the controller is alive.

Is it possible to add an init method or something else?

It is not clear what you mean. However:

  • The handleRequest controller is called to start the request.
  • If you declare a bean (for example, a bean controller) as ApplicationContextAware , it will be called back to inform ApplicationContext.
  • If you declare any bean as ServletContextAware , it will be called back to inform it of ServletContext.
  • If you declare any bean as an InitializingBean , it will be called back when all properties are set.

And there are undoubtedly other callbacks and interceptors that can be used to trigger some initialization / context setting delay.

(I'm not sure how these callbacks / bindings appear in the annotation ... but I'm sure they do.

+3
source

Source: https://habr.com/ru/post/1315516/


All Articles