我有:
@ControllerAdvice(assignableTypes = CommentController.class)
public class Test {
private final ThreadServices threadServices;
private final UserServices userServices;
@Autowired
public Test(ThreadServices threadServices, UserServices userServices) {
this.threadServices = threadServices;
this.userServices = userServices;
}
@ModelAttribute
public CommentCreateBindingModel fill(CommentCreateBindingModel bindingModel, @PathVariable String threadId, Principal principal){
UserServiceModel creator = this.userServices.findUserByUsername(principal.getName());
ThreadServiceModel thread = this.threadServices.findById(threadId);
bindingModel.setCreator(creator);
bindingModel.setThread(thread);
return bindingModel;
}
}
和控制器:
@Controller
public class CommentController extends BaseController {
private final CommentServices commentServices;
private final ModelMapper modelMapper;
private final ThreadServices threadServices;
@Autowired
public CommentController(CommentServices commentServices, ModelMapper modelMapper, ThreadServices threadServices) {
this.commentServices = commentServices;
this.modelMapper = modelMapper;
this.threadServices = threadServices;
}
@PreAuthorize("hasAuthority('MODERATOR') or @commentServicesImp.findById(#commentId).creator.username.equals(principal.username)")
@PostMapping(URLConstants.COMMENT_DELETE_POST)
public String proceedCommentDeletion(@PathVariable String commentId) {
CommentServiceModel commentServiceModel = this.commentServices.findById(commentId);
this.commentServices.delete(commentId);
String threadId = commentServiceModel.getThread().getId();
String redirectUrl = URLConstants.THREAD_READ_GET.replace("{threadId}", threadId);
return super.redirect(redirectUrl);
}
@PreAuthorize("isAuthenticated()")
@PostMapping(value = URLConstants.THREAD_CREATE_COMMENT_POST, produces = "application/json")
@ResponseBody
public String proceedCommentCreation(@PathVariable String threadId,
@Valid @ModelAttribute CommentCreateBindingModel commentCreateBindingModel,
BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return new Gson().toJson(false);
}
this.commentServices.create(commentCreateBindingModel);
return new Gson().toJson(true);
}
}
问题在于,填充方法每次在我的控制器中被调用时都会执行,这会导致异常。我希望仅当方法包含CommentCreateBindingModel
时才执行方法填充