When to implement WebMvcConfigurer to configure Spring MVC?

13,121

Implementing WebMvcConfigurer lets you configure Spring MVC configuration. For all the unimplemented methods, the default values are used.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.html


As for the @Bean public ViewResolver viewResolver(), the location of this bean definition is actually not related to this class at all and can be placed anywhere where Spring is scanning for beans. The guide is perhaps a bit confusing and leaves the impression that these two things are somehow related.

Share:
13,121
Admin
Author by

Admin

Updated on December 12, 2022

Comments

  • Admin
    Admin over 1 year

    I'm learning about Spring MVC with Java configuration (no xml) and I have a simple question. I see 2 approaches of making Spring bean configuration:

    approach 1:

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages="com.demo.springmvc")
    public class DemoAppConfig {
    
        // define a bean for ViewResolver
    
        @Bean
        public ViewResolver viewResolver() {
    
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    
            viewResolver.setPrefix("/WEB-INF/view/");
            viewResolver.setSuffix(".jsp");
    
            return viewResolver;
        }
    
    }
    

    approach 2:

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.example")
    public class SpringConfig implements WebMvcConfigurer{
    
        @Bean
        public ViewResolver viewResolver() {
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setViewClass(JstlView.class);
            viewResolver.setPrefix("/WEB-INF/pages/");
            viewResolver.setSuffix(".jsp");
    
            return viewResolver;
        }
    
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    
    }
    

    So one way is by implementing the WebMvcConfigurer interface and another way in not implementing the WebMvcConfigurer interface. I want to ask you what is the difference? What's happen when I implement this interface and what's happen when I don't implement it. Any feedback will be appreciated.