java - 无法使用@EnableWebMvc 配置运行 SPRING BOOT 应用程序

标签 java spring-mvc spring-boot gradle

我是 spring boot 的新手,我非常有兴趣学习这项技术。这是问题所在,我得到了一个带有@configuration 标签的配置文件。所以当我尝试添加 @enablemvc 注释或者如果我在 spring boot 应用程序中添加带有 @enablemvc annoation 的新文件时,我无法运行该应用程序。如果有人能帮我解决这个问题,我真的很感激。

日志

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.configureAsChildIfNecessary(SpringApplicationBuilder.java:147) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at com.boot.main.ClientMain.main(ClientMain.java:31) [bin/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.9.RELEASE.jar:1.5.9.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 23 common frames omitted
Caused by: org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry.getHandlerMapping(ResourceHandlerRegistry.java:150) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:446) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c7bc0fe.CGLIB$resourceHandlerMapping$28(<generated>) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c7bc0fe$$FastClassBySpringCGLIB$$d042f6eb.invoke(<generated>) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c7bc0fe.resourceHandlerMapping(<generated>) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 24 common frames omitted
Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.web.context.support.WebApplicationObjectSupport.getWebApplicationContext(WebApplicationObjectSupport.java:112) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.context.support.WebApplicationObjectSupport.getServletContext(WebApplicationObjectSupport.java:128) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.initContentNegotiationStrategy(ResourceHttpRequestHandler.java:306) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.afterPropertiesSet(ResourceHttpRequestHandler.java:268) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry.getHandlerMapping(ResourceHandlerRegistry.java:147) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 35 common frames omitted

自动配置.java

@Configuration
//@EnableAutoConfiguration
@ConditionalOnClass(MyClass.class)
@EnableConfigurationProperties(MyProperties.class)
@ComponentScan({ "com.boot", "com.jspClient" })
@SpringBootApplication
public class AutoConfiguration {

    private static Log log = LogFactory.getLog(AutoConfiguration.class);




    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    /*@Bean  
    public UrlBasedViewResolver urlBasedViewResolver() {  
      UrlBasedViewResolver resolver = new UrlBasedViewResolver();  
      resolver.setPrefix("/WEB-INF/jsp/");  
      resolver.setSuffix(".jsp");
      resolver.setViewClass(JstlView.class);  
      return resolver;  
    }*/


    //http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/simple-mapping-exception-resolver/
    //https://github.com/paulc4/mvc-exceptions/blob/master/src/main/java/demo/config/ExceptionConfiguration.java
    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
      SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
      Properties errorMaps = new Properties();
      errorMaps.setProperty(UserNotFoundException.class.getName(), "myError");
      errorMaps.setProperty("Exception", "generic_error");
      resolver.setExceptionMappings(errorMaps);
      resolver.setDefaultErrorView("generic_error");
      resolver.setExceptionAttribute("exc");
      return resolver;
   }

    @Bean
    WebMvcConfigurer configurer () {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addResourceHandlers (ResourceHandlerRegistry registry) {
                ResourceHandlerRegistration resourceRegistration  = registry
                        .addResourceHandler("/pages/**")
                        .addResourceLocations("/resources/","classpath:/images/")  //Configuring Multiple Locations for a Resource
                        .setCachePeriod(3600);            //The resources served will be cached in the browser for 3600 seconds
                registry.addResourceHandler("resources/**").addResourceLocations("/resources/");
                //registry.addResourceHandler("/css/**").addResourceLocations("/css/");
                //registry.addResourceHandler("/img/**").addResourceLocations("/img/");
                //registry.addResourceHandler("/js/**").addResourceLocations("/js/");
            }
        };
    }
}

AppConfig.java

@Configuration 
@ComponentScan("com.boot.controllers") 
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {  

    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
      SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
      Properties errorMaps = new Properties();
      errorMaps.setProperty("ElectricityNotFoundException", "error");
      errorMaps.setProperty("NullPointerException", "error");
      resolver.setExceptionMappings(errorMaps);
      resolver.setDefaultErrorView("globalerror");
      resolver.setExceptionAttribute("exc");
      return resolver;
   }
}

WebAppInitializer.java

public class WebAppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {  
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
        ctx.register(AppConfig.class);  
        ctx.setServletContext(servletContext);    
        Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
        dynamic.addMapping("/");  
        dynamic.setLoadOnStartup(1);  
   }  
} 

ClientMain.java

@ComponentScan("com.boot") // to scan controller under com.boot -> com.boot.controllers
@SpringBootApplication
public class ClientMain {

    private static SpringApplicationBuilder start(Class<?>... sources) {
        return new SpringApplicationBuilder(ClientMain.class)
            .child(sources);
    }

    public static void main(String[] args) throws Exception {

        // using just Spring alone
        /*ApplicationContext context = new AnnotationConfigApplicationContext(AutoConfiguration.class);

    }

}

JspClientMain.java

@ComponentScan("com.boot") 
@SpringBootApplication
public class JspClientMain {

    public static void main(String[] args) {
        SpringApplication.run(JspClientMain.class, args);
    }
}

最佳答案

通常,@EnableWebMvc 不应在 Spring boot 应用程序中使用。我引用 article by Boz Hogan :

It turns out that Spring Boot doesn’t mix well with the standard Spring MVC @EnableWebMvc. What happens when you add the annotation is that Spring Boot's autoconfiguration is disabled.

The bad part (that wasted me a few hours) is that in no guide you can find that explicitly stated. (...)

这是来自 Spring Boot documentation 的引述:

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. (...)

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

因此,要在 Spring Boot 应用程序中使用 @EnableWebMvc,您需要完全控制 Spring MVC——我读到的是您需要Spring wiz

我们遇到了一个 Spring boot 1.5.9 应用程序的问题,该应用程序依赖于一个共享库,该共享库包含一个用 @EnableWebMvc 注释的类。删除注释解决了问题。

关于java - 无法使用@EnableWebMvc 配置运行 SPRING BOOT 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721984/

相关文章:

java - 从 Java 程序访问 NFS 共享

java - 如何使用 switch 语句并获得正确的输出?

java - EJB 异常 - 尝试使用具有空 session 的间接遍历关系。

java - 关闭浏览器后HttpSession发生变化

spring-boot - 如何在spring RestDoc(asciidoc)中折叠TOC(目录)?

Java:HashMap 内联初始化的性能影响

java - 如何在 spring-data-rest 中将 Page<ObjectEntity> 映射到 Page<ObjectDTO>

Spring MVC-Joda 日期时间错误消息无效日期

java - 为什么我在尝试从 angular5 向 spring-boot 发送 PUT 请求时收到未经授权的消息?

java - 访问 BeanFactoryPostProcessor 中的属性