我正在尝试使用方法上的@ModelAttribute Annontation初始化对象。当调用URL“ / p / PPP / scope”时,会发生奇怪的事情。调用@ModelAttribute方法时,似乎不会实例化ProjectService,但调用show()方法时,ProjectService在那里。有谁知道这有什么问题吗?
以下是日志语句:
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;
}
}
最佳答案
具有ModelAttibute批注的所有方法必须是公共的。
因此,当方法getProject为公共方法时,它将可以正常工作:
@ModelAttribute("project")
public Project getProject( ...