When to implement WebMvcConfigurer to configure Spring MVC?
Asked Answered
M

2

8

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.

Mealworm answered 1/7, 2019 at 9:30 Comment(1)
Good question which lacks the right answer, I'm wondering too what's the difference !Viewless
B
1

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.

Burkett answered 1/7, 2019 at 9:56 Comment(0)
C
0

While you are using just EnableWebMvc annotation, you would tell the framework just use the default configuration but while implementing WebMvcConfigurer or extending for example WebMvcConfigurerAdapter class to Override methods, you will tell the framework just use your custom methods while creating beans

Cultigen answered 31/3, 2022 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.