先看这么一段代码:
@Service public class AccountService { private String message; public void foo1() { if (true) { this.message = "a"; } else { this.message = "b"; } } public void foo2() { // 修改this.message的代码... // ... ... } }
accountService.foo1(); model.addAttribute(accountService.getMessage());
那么就有线程安全的危险了。
@Service @Scope("request") public class AccountService { private String message;
class MessageWrapper { private String message; public MessageWrapper(String msg) { this.message = msg; } // 只提供get方法 public String getMessage() { return this.message; } }
@Service public class AccountService { public MessageWrapper foo1() { if (true) { return new MessageWrapper("a"); } else { return new MessageWrapper("b"); } // ... ... }
Spring MVC不要在@Service bean中保存状态
原文:http://blog.csdn.net/neosmith/article/details/41018683