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.

2 Answers2

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.

käyrätorvi
  • 371
  • 1
  • 9
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

sina zarei
  • 87
  • 1
  • 5