Home > Software design >  why the model bean is not found in the spring boot app?
why the model bean is not found in the spring boot app?

Time:09-27

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";
    }
}

UPDATE: but this works! It means that the bean is created.(Of course, after we delete the model field from the constructor and the class)

@GetMapping("contact")
    public String displayPage(Model model) {
        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.

CodePudding user response:

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;

    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";
    }
}

When defining the model as dependency in the constructor, a bean of that type (and name) is looked up in the application context. Only a single instance in injected.

However, the model is request-specific and therefore needs to be injected into the handler method itself. Think @Scope("request").

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

More details can be found in the Spring Web MVC framework docs: 17.3 Implementing Controllers

  • Related