使Spring 3 MVC控制器方法具有事务性


问题内容

我正在使用Spring 3.1,并编写了我的DAO和服务层(事务性)。

但是在特殊情况下,为了避免延迟的init异常,我必须制作一个spring
mvc请求处理程序方法@transactional。但是它无法将事务附加到该方法。方法名称为ModelAndView
home(HttpServletRequest请求,HttpServletResponse响应)。
http://forum.springsource.org/showthread.php?46814-Transaction-in-MVC-
Controller 从此链接看来,不可能将事务(默认情况下)附加到mvc方法。该链接中建议的解决方案似乎是针对Spring
2.5(覆盖handleRequest)的。任何帮助将不胜感激。谢谢

@Controller
public class AuthenticationController { 
@Autowired
CategoryService categoryService;    
@Autowired
BrandService brandService;
@Autowired
ItemService itemService;

@RequestMapping(value="/login.html",method=RequestMethod.GET)
ModelAndView login(){       
    return new ModelAndView("login.jsp");       
}   
@RequestMapping(value="/home.html",method=RequestMethod.GET)
@Transactional
ModelAndView home(HttpServletRequest request, HttpServletResponse response){
    List<Category> categories = categoryService.readAll();
    request.setAttribute("categories", categories);     
    List<Brand> brands = brandService.readAll();
    request.setAttribute("brands", brands);     
    List<Item> items = itemService.readAll();
    request.setAttribute("items", items);
    Set<Image> images = items.get(0).getImages();
    for(Image i : images ) {
        System.out.println(i.getUrl());
    }
    return new ModelAndView("home.jsp");    
}

问题答案:

您需要实现一个接口,以便Spring可以将其用作代理接口:

@Controller
public interface AuthenticationController {
  ModelAndView home(HttpServletRequest request, HttpServletResponse response);
}

@Controller
public class AuthenticationControllerImpl implements AuthenticationController {

@RequestMapping(value="/home.html",method=RequestMethod.GET)
@Transactional
@Override
ModelAndView home(HttpServletRequest request, HttpServletResponse response){
.....
}
}