Close

Using Spring 5.0 WebMvcConfigurer default methods

[Last Updated: Dec 12, 2017]

Since Spring 5.0, WebMvcConfigurer has Java 8 default methods. That means, for MVC configuration, we can implement this interface directly without extending WebMvcConfigurerAdapter (deprecated in 5.0).

Example

Implementing WebMvcConfigurer

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {

  @Override
  public void configureViewResolvers(ViewResolverRegistry registry) {
      registry.jsp("/WEB-INF/views/", ".jsp");
  }

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
      //this will map uri to jsp view directly without a controller
      registry.addViewController("/hi")
              .setViewName("hello");
  }
}

src/main/webapp/WEB-INF/views/hello.jsp

<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
Hello! <br/>
<%= new java.util.Date().toString() %>
</body>
</html>

Output

Example Project

Dependencies and Technologies Used:

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

Spring Mvc Configurer Default Methods Example Select All Download
  • spring-5-web-mvc-configurer-default-methods
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyWebConfig.java
          • webapp
            • WEB-INF
              • views

    See Also