我是Spring的新手,有一些基本的問題。在下面給出的Spring例子之一中,我注意到EmployeeManager是Autowired。Spring Singleton bean線程安全
問:
- 的EmployeeManager範圍不給,所以我會假設默認範圍是辛格爾頓和Spring bean是不是線程安全的。這個假設是正確的嗎?
EmployeeManager被定義爲可以被多個線程訪問的Servlet的一部分。 假設多個線程同時使用值「1」「2」&「3」調用「刪除」方法,併爲每個線程(自其SINGLETON以來)生成同一個EmployeeManager實例,該刪除值將被執行Spring如何處理這種情況?
@Controller public class EditEmployeeController { @Autowired private EmployeeManager employeeManager; @RequestMapping(value = "/", method = RequestMethod.GET) public String listEmployees(ModelMap map) { map.addAttribute("employee", new EmployeeEntity()); map.addAttribute("employeeList", employeeManager.getAllEmployees()); return "editEmployeeList"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addEmployee(@ModelAttribute(value="employee") EmployeeEntity employee, BindingResult result) { employeeManager.addEmployee(employee); return "redirect:/"; } @RequestMapping("/delete/{employeeId}") public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId) { employeeManager.deleteEmployee(employeeId); return "redirect:/"; } public void setEmployeeManager(EmployeeManager employeeManager) { this.employeeManager = employeeManager; } }
EmployeeManager -
public interface EmployeeManager {
public void addEmployee(EmployeeEntity employee);
public List<EmployeeEntity> getAllEmployees();
public void deleteEmployee(Integer employeeId);
}
@Service
public class EmployeeManagerImpl implements EmployeeManager
{
@Autowired
private EmployeeDAO employeeDAO;
@Override
@Transactional
public void addEmployee(EmployeeEntity employee) {
employeeDAO.addEmployee(employee);
}
@Override
@Transactional
public List<EmployeeEntity> getAllEmployees() {
return employeeDAO.getAllEmployees();
}
@Override
@Transactional
public void deleteEmployee(Integer employeeId) {
employeeDAO.deleteEmployee(employeeId);
}
public void setEmployeeDAO(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
}
也許閱讀答案http://stackoverflow.com/questions/11508405/are-spring-mvc-controllers-singletons將有所幫助。 – Atul 2014-11-24 08:30:10