Nikhil
Nikhil

Reputation: 310

Can not understand difference in behavior between : @EnableWebMvc and <annotation-driven />

I was looking for annotation based approach for <interceptors> and then found the way here

So I used it and its working, but there is a catch.

When I do;

@Configuration
@EnableWebMvc
public class WebApplicationConfig extends WebMvcConfigurerAdapter{
     ....
}

and there is no <annotation-driven /> tag in servlet-context.xml then it works perfectly fine and url are intercepted and corressponding pre-post logic works as implemented in "WebApplicationConfig " - my custom interceptor.

But if I remove @EnableWebMvc and add <annotation-driven /> then logically speaking application does not work, meaning no url's are intercepted its like "WebApplicationConfig " class is not even there.

and off cource if I keep both @EnableWebMvc and <annotation-driven /> then I get exception while deploying the application. :

    ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
    ..........
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerExceptionResolver 

org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.handlerExceptionResolver()] threw exception;

 nested exception is java.lang.ClassCastException:

 org.springframework.web.accept.ContentNegotiationManagerFactoryBean$$EnhancerByCGLIB$$56a95502 cannot be cast to org.springframework.web.accept.ContentNegotiationManager

So why url's are not intercepted , when I used <annotation-driven /> instead of @EnableWebMvc

Also if I go with @EnableWebMvc and no <annotation-driven />, then using @EnableWebMvc at place of declaring class WebApplicationConfig is right place?

Upvotes: 1

Views: 3481

Answers (2)

M. Deinum
M. Deinum

Reputation: 124526

Although @EnableWebMvc and <mvc:annotation-driven /> have the same purpose, enabling support for @Controller with @RequestMapping. They aren't complementary either use Java based config or xml, mixing them will not work.

The WebMvcConfigurerAdapter or actually the WebMvcConfigurer is only designed and detected when using @EnableWebMvc not when using <mvc:annotation-driven />.

When trying to enable/use them both you will run into issues with duplicate comopnents registered (like the RequestMappingHandlerAdapter and such).

Upvotes: 3

alizelzele
alizelzele

Reputation: 923

@EnableWebMvc and <mvc:annotation-driven/> are the same thing for activating @controller and so on.

are you sure both xml and config files are loaded at load time?

maybe in your xml file address to the controller base package is wrong or something like that. try adding controller class as a bean and see if it is working

Upvotes: 0

Related Questions