Java 由ModelAttribute注释的多个方法。如何设置方法';s调用顺序
我有这么一个@Controller:Java 由ModelAttribute注释的多个方法。如何设置方法';s调用顺序,java,spring,spring-mvc,controller,Java,Spring,Spring Mvc,Controller,我有这么一个@Controller: @Controller public class CandidateMenuController{ @ModelAttribute(value = "vacancies") public Set<Vacancy> loadVacancies() { return vacancyService.getAll(); } @ModelAttribut
@Controller
public class CandidateMenuController{
@ModelAttribute(value = "vacancies")
public Set<Vacancy> loadVacancies() {
return vacancyService.getAll();
}
@ModelAttribute(value = "vacanciesForCandidate")
public Set<Vacancy> vacanciesForCandidate(@RequestParam(required = false) List<Integer> vacanciesSelected,
@ModelAttribute("vacancies")Set<Vacancy> allVacancies ) {
.....
}
}
显然,这取决于@ModelAttributes方法调用的顺序
我知道我可以在@modeldattribute方法中手动调用必要的方法,但是
如何管理@modeldattribute方法调用?您不能,基本上方法上的
@modeldattribute
注释不能与参数上的@modeldattribute
注释组合。我也强烈反对这种做法。它使您的控制器对更改非常脆弱,并且容易出错(即imho)
为什么不简单地编写一个返回void的方法,将模型作为参数包含在内,然后执行呢
@ModelAttribute
public void referenceData(@RequestParam(required=false) List<Integer> vacanciesSelected, Model model) {
Set<Vacancy> vacancies= vacancyService.getAll();
model.addAttribute("vacancies", vacancies);
if (vacanciesSelected != null && !vacanciesSelected.isEmpty() ) {
Set<Vacancy> vacanciesForCandidate = // Do something with the set
model.addAttribute("vacanciesForCandidate", vacanciesForCandidate);
}
}
@modeldattribute
public void referenceData(@RequestParam(required=false)List vacancesselected,Model Model){
设置空缺=vacancyService.getAll();
model.addAttribute(“空缺”,空缺);
if(vacancesselected!=null&!vacancesselected.isEmpty()){
Set vacancesforcandidate=//对集合执行某些操作
model.addAttribute(“vacancesforcandidate”,vacancesforcandidate);
}
}
不依赖方法排序的稳健解决方案 此功能被视为一种新功能,最新版本的spring framework支持@ModelAttribute注释方法的相互依赖性
有关更多信息,请参阅我在主题中撰写的有关此解决方案的文章。我认为spring mvc的创建者必须禁止在方法params中使用注释ModelAttribute的注释ModelAttribute。我不理解您的评论。在我的主题中,我写了关于这个解决方案的文章,为什么它会导致编译错误。它是完全有效的Java代码,并且可以正常工作,但您不应该这样做。编译器对此无能为力,唯一能做的就是在启动应用程序时解析@modeldattribute方法时出错。可能存在重复的。。。不同的用户(?),相同的代码,基本上相同的问题。有我问的原因。在这里我理解原因,但寻找解决办法
@ModelAttribute
public void referenceData(@RequestParam(required=false) List<Integer> vacanciesSelected, Model model) {
Set<Vacancy> vacancies= vacancyService.getAll();
model.addAttribute("vacancies", vacancies);
if (vacanciesSelected != null && !vacanciesSelected.isEmpty() ) {
Set<Vacancy> vacanciesForCandidate = // Do something with the set
model.addAttribute("vacanciesForCandidate", vacanciesForCandidate);
}
}