Is the Controller class of spring mvc Singleton?
I have been using Spring MVC for some time. I have been using Struts2 for a long time. In struts2, actions are prototype. This is because of thread security issues. For Spring MVC, beans are all (singleton) by default) for Singleton, is the Controller class injected with @ Controller annotation label implemented by Singleton?
Test results show that controller in spring3 is Singleton by default. If a controller has a private variable I, all the I variables used when all requests reach the same controller are shared, that is, if a request modifies the variable a, the modified content can be read in other requests. If @ Scope ("prototype") is added before @ Controller, you can change the singleton mode to the singleton mode.
The following is the test procedure, code, and result.
For a singleton type class, the class variables in the Controller class should be shared. If they are not shared, the Controller class is not Singleton. The following is the test code:
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ExampleAction { private int singletonInt=1; @RequestMapping(value = /test) @ResponseBody public String singleton(HttpServletRequest request, HttpServletResponse response) throws Exception { String data=request.getParameter(data); if(data!=null&&data.length()>0){ try{ int paramInt= Integer.parseInt(data); singletonInt = singletonInt + paramInt; } catch(Exception ex){ singletonInt+=10; } }else{ singletonInt+=1000; } return String.valueOf(singletonInt); }}
The returned results are as follows.
First time: singletonInt = 15
Second time: singletonInt = 30
Third time: singletonInt = 45
From the above results, we can know that the singletonInt status is shared, so the Controller is a singletonInt.
If the Controller class is a Singleton, multiple threads request the same method in the same Controller class to check whether the thread is blocked.
@RequestMapping(value = /sleepdata)@ResponseBodypublic String switcher(HttpServletRequest request , HttpServletResponse response) throws Exception { String sleep = request.getParameter(sleep); if (sleep.equals(on)) { Thread.currentThread().sleep(100000); return sleep on; } else { return sleep; }}