Spring MVC does not save the status in @ Service bean.
Let's take a look at this piece of code:
@ Servicepublic class AccountService {private String message; public void foo1 () {if (true) {this. message = "a";} else {this. message = "B" ;}} public void foo2 () {// modify this. message code... //......}}
If you want to call AccountService in @ Controller as follows:
accountService.foo1();model.addAttribute(accountService.getMessage());
There is a thread security risk.
In Spring, the default scope of bean is singleton, that is, there is only one bean instance in the container. In the Java Web environment, the web server creates a thread for each request to process it. In this way, calling the @ Service bean method in @ Controller results in multiple threads executing the @ Service method. For example, thread A is executing the foo1 () method, thread B is executing the foo2 () method. Then the problem arises. When multiple threads read and write the message member variable at the same time, the getMessage () method may return an error value.
Solution 1. Change the scope of @ Service bean to "request", that is:
@Service@Scope("request")public class AccountService {private String message;
In this way, Spring creates an AccoutService object for each request, and each thread has its own message variable, so that no error will occur. However, the disadvantage is that the overhead of creating @ Service bean is usually large, which may lead to a decline in program performance.
2. Use Immuable Object to encapsulate message variables and define the following classes:
Class MessageWrapper {private String message; public MessageWrapper (String msg) {this. message = msg;} // only the get method public String getMessage () {return this. message ;}}
The foo1 () method of AccountService is modified as follows:
@Servicepublic class AccountService {public MessageWrapper foo1() {if (true) {return new MessageWrapper("a");} else {return new MessageWrapper("b");}// ... ...}
In this way, thread security issues can be avoided without overhead.