在Spring MVC中有没有办法做到这一点?我想要@Autowired RedirectAttributes:
@Controller
public class RegistrationController {
@Autowired private RedirectAttributes redirectAttributes;
@RequestMapping(value = SIGNUP_ROUTE, method = RequestMethod.POST)
public String signUpPage(ModelMap modelMap, User user) {
save(user);
redirectAttributes.addFlashAttribute("success", "Very good");
return "redirect:/sign-in";
}
}
我得到的异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registrationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.servlet.mvc.support.RedirectAttributes com.myhome.controller.RegistrationController.redirectAttributes; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.support.RedirectAttributes] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
最佳答案
在代码中注入依赖关系的一种方法是添加类RedirectAttributes的额外参数
@Controller
public class RegistrationController {
@RequestMapping(value = SIGNUP_ROUTE, method = RequestMethod.POST)
public String signUpPage(ModelMap modelMap, RedirectAttributes rda, User user) {
save(user);
rda.addFlashAttribute("success", "Very good");
return "redirect:/sign-in";
}
}