Spring Boot - BeanNameViewResolver Auto registration

[Updated: Nov 20, 2017, Created: Nov 19, 2017]

In Spring Boot, BeanNameViewResolver bean is registered by default, that means we can use a View's bean name as a view name by default. In a plain Spring MVC application we have to explicitly register this bean ourselves (example here).

Example

We are going to create a custom View in this example.

A custom View

package com.logicbig.example;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Component("myCustomView")
public class MyCustomView implements View {

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

  @Override
  public void render(Map<String, ?> map, HttpServletRequest httpServletRequest,
                     HttpServletResponse httpServletResponse) throws Exception {
      PrintWriter writer = httpServletResponse.getWriter();
      writer.write("msg rendered in MyCustomView: " + map.get("msg"));
  }
}

A Controller

@Controller
public class MyController {

  @GetMapping("/")
  public String handle(Model model) {
      model.addAttribute("msg", "test msg from controller");
      return "myCustomView";
  }
}

Java Config and main class

@SpringBootApplication
public class ExampleMain {

  public static void main(String[] args) throws InterruptedException {
      SpringApplication.run(ExampleMain.class, args);
  }
}

Output

Example Project

Dependencies and Technologies Used :

  • spring-boot-starter-web 1.5.8.RELEASE: Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container [Description from spring-boot-starter-web-1.5.8.RELEASE.pom]
    Corresponding Spring version: 4.3.12.RELEASE
  • JDK 1.8
  • Maven 3.3.9

Boot Bean Name View Resolver Example Select All Download
  • boot-bean-name-view-resolver-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also