Nowshad Hossain
Nowshad Hossain

Reputation: 43

use RedirectAttributes as bean spring mvc

Is there a way to do this in spring mvc; I want to @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";
    }
}

Exception I get:

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)

Upvotes: 3

Views: 647

Answers (1)

Pedro Machado
Pedro Machado

Reputation: 156

One way to inject the dependency in your code could be adding an extra parameter of the class 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";
    }
}

Upvotes: 1

Related Questions