Spring MVC - BeanNameViewResolver Example

[Last Updated: Sep 2, 2017]

BeanNameViewResolver maps a view name to a bean name in the current application context. The matching bean must implement the View interface so that it can be executed by DispatcherServlet to render the view.


A custom view

public class MyCustomView implements View {

  public String getContentType() {
      return "text/html";

  public void render(Map<String, ?> model, HttpServletRequest request,
                     HttpServletResponse response) throws Exception {
      PrintWriter writer = response.getWriter();
      writer.println("This is my custom dummy view.<br/>");
      writer.println("<h3>Model attributes</h3>");
      for (Map.Entry<String, ?> entry : model.entrySet()) {
          writer.printf("%s = %s<br/>", entry.getKey(), entry.getValue());

Registering BeanNameViewResolver and the view as Bean

public class MyWebConfig {

  public ViewResolver viewResolver() {
      return new BeanNameViewResolver();

  public View myCustomView() {
      return new MyCustomView();

Alternative way to register BeanNameViewResolver

As an alternative to above configuration, we can enable BeanNameViewResolver by overriding configureViewResolvers() method of WebMvcConfigurerAdapter:

public class MyWebConfig extends WebMvcConfigurerAdapter {

    public void configureViewResolvers (ViewResolverRegistry registry) {

    public View myCustomView() {
        return new MyCustomView();

Writing a Controller

The controller that is going to return our bean name as the view name.

public class MyController {
  public String handleRequest (Model model) {
      model.addAttribute("msg", "A message from the controller");
      return "simpleView";


Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

BeanNameViewResolver Example Select All Download
  • bean-view-resolver-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also