1

我正在尝试使用方法上的 @ModelAttribute Annontation 初始化对象。当调用 URL "/p/PPP/scope" 时会发生奇怪的事情。ProjectService 在调用@ModelAttribute 方法时似乎没有被实例化,但在调用 show() 方法时它就在那里。有人知道这有什么问题吗?

以下是日志语句:

12:32:19 [DEBUG] ScopeController - getProject() - loading project for 'PPP'
12:32:19 [DEBUG] ScopeController - getProject() - projectService initialized? null
12:32:21 [DEBUG] ScopeController - show() - projectService initialized? ...project.ProjectService@20f2442e

和来源:

@Controller
@RequestMapping("/p/{abbr}/scope")
@SessionAttributes("project")
public class ScopeController {

    public static final String SHOW_PROJECT_PAGE = "/projects/scope/show";

    private static final Logger log = LoggerFactory.getLogger(ScopeController.class);

    @Autowired
    private ProjectService projectService;

    @ModelAttribute("project")
    private Project getProject(@PathVariable(value = "abbr") String abbr) {
        log.debug("getProject() - loading project for '{}'", abbr);
        log.debug("getProject() - projectService initialized? {}", projectService);
        // should call this method:
        // return projectService.find(abbr);
        return new Project();
    }

    @RequestMapping(method = RequestMethod.GET)
    @Transactional
    public String show() throws BindException {
        log.debug("show() - projectService initialized? {}", projectService);
        return SHOW_PROJECT_PAGE;
    }
}
4

4 回答 4

1

所有带有 ModelAttibute 注解的方法都必须是公共的。

所以当方法 getProject 是公开的 - 它会正常工作:

 @ModelAttribute("project")
 public Project getProject( ...
于 2014-04-24T15:17:02.340 回答
0

也许尝试一些事情。

  1. 更改签名:
    • 私人项目 getProject 到
    • 公共@ResponseBody项目
  2. 从控制器中删除 @Transactional 并将它们移动到需要它们的任何服务方法。(可以说是更好的设计实践 - 怀疑它是否会导致您描述的问题)
  3. 将 @ModelAttribute("Project") 注释移动到 Project 类

    • @ModelAttribute("Project") public Project get Project(){ return new Project(); }

所以它看起来像:

@Controller
@RequestMapping("/p/{abbr}/scope")
@SessionAttributes("project")
public class ScopeController {

public static final String SHOW_PROJECT_PAGE = "/projects/scope/show";

private static final Logger log = LoggerFactory.getLogger(ScopeController.class);

@Autowired
private ProjectService projectService;

@RequestMapping(value = "/<yourUri for getProject>", method = RequestMethod.GET)
public @ResponseBody Project get(@PathVariable(value = "abbr") String abbr) {
    return getProject(abbr);
}

private Project getProject(String abbr) {
    log.debug("getProject() - loading project for '{}'", abbr);
    log.debug("getProject() - projectService initialized? {}", projectService);
    // should call this method:
    // return projectService.find(abbr);
    return new Project();
}

@RequestMapping(method = RequestMethod.GET)
@Transactional
public String show() throws BindException {
    log.debug("show() - projectService initialized? {}", projectService);
    return SHOW_PROJECT_PAGE;
}

}

//In your Project class 
@ModelAttribute("project")
public class Project {
//your class stuff
}
于 2013-09-14T12:37:45.590 回答
0

一方面,我会将@Transactional注释放在存储库/数据访问层中,因为这是基于 Spring MVC 注释的良好分层应用程序的规范。此外,您的@PathVariable注释用于检索在控制器的基本 URI 之后的 URI 中传递的值。因此,在不拦截 URI 模式的私有辅助方法中使用此注释没有什么意义。

于 2013-09-14T13:24:01.187 回答
0

所以在玩了之后我找到了解决方案。问题是@ModelAttribute 中的名称。删除“项目”后,该方法按预期工作。由于对“getProject()”方法的混淆,我做了一些重构以使该方法的意图更加清晰。这是带有附加注释的完整类:

@Controller
@RequestMapping("/p/{abbr}/scope")
public class ScopeController {

    private static final String SHOW_PROJECT_PAGE = "/projects/scope/show";

    private static final Logger log = LoggerFactory.getLogger(ScopeController.class);

    @Autowired
    private ProjectService projectService;

    // method is called before show() and update()
    @ModelAttribute
    private void initProject(@PathVariable(value = "abbr") String abbr, Model model) {
        log.debug("loading project for '{}'", abbr);
        // load the project JPA entity from the database, will be merged with the  
        // updated form values in the POST request. By doing this, I can asure
        // that the primary key (the ID) and the related objects are present as 
        // needed for the em.saveOrUpdate() in the projectService.save() method.
        model.addAttribute("project", projectService.find(abbr));
    }

    @RequestMapping(method = RequestMethod.GET)
    public String show() throws BindException {
        // shows the project scope form with the project 
        // added in 'initProject()'
        return SHOW_PROJECT_PAGE;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String update(
            // the project with the updated form values and the JPA ID and JPA 
            // relations as loaded in the initProject()
            @Valid @ModelAttribute Project project, BindingResult result, 
            RedirectAttributes redirectAttrs)
            throws MethodArgumentNotValidException {

        redirectAttrs.addFlashAttribute(project);

        try {
            if (!result.hasErrors()) {
                projectService.save(project);
            }
        }
        catch (Exception e) {
            log.error(e.toString());
            throw new MethodArgumentNotValidException(null, result);
        }

        log.debug("project '{}' updated", project.getAbbreviation());
        return SHOW_PROJECT_PAGE;
    }
}

谢谢大家的回答。

于 2013-09-15T12:50:22.717 回答