why the model bean is not found in the spring boot app?

Viewed 12

My question is, isn't an object created from the model in spring? So why does it give an error when it tries to inject in the following program?

@Controller
public class ContactController {
    private final ContactService service;
    private Model model;

    public ContactController(ContactService service, Model model) {
        this.service = service;
        this.model = model;
    }

    @GetMapping("contact")
    public String displayPage() {
        model.addAttribute("contact", new Contact());
        return "contact";
    }
}

error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in com.isoft.controllers.ContactController required a bean of type 'org.springframework.ui.Model' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.ui.Model' in your configuration.
1 Answers

The model is not a dependency to your controller. You need to return a new model, when the method is called. Otherwise, different requests would all see the same model (race-conditions, security issues, and all other kinds of nasty problems)

@Controller
public class ContactController {
    private final ContactService service;
    private Model model;

    public ContactController(final ContactService service) {
        this.service = service;
    }

    @GetMapping("contact")
    public String displayPage() {
        final Model model = new Model();
        model.addAttribute("contact", new Contact());
        return "contact";
    }
}
Related