spring 版本5.3,在使用spring与spring mvc 整合的过程中发现报此错误
����: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in com.mvc.test.WebConfig: 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 java.lang.IllegalStateException: No ServletContext set
8�� 27, 2020 2:00:12 ���� org.apache.catalina.core.ContainerBase startInternal
����: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:911)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:890)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1403)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
... 6 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in com.mvc.test.WebConfig: 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 java.lang.IllegalStateException: No ServletContext set
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at com.mvc.test.MyWebApplicationInitializer.onStartup(MyWebApplicationInitializer.java:18)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5178)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
... 22 more
Caused by: java.lang.IllegalStateException: No ServletContext set
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:533)
at com.mvc.test.WebConfig$$EnhancerBySpringCGLIB$$73e81027.CGLIB$resourceHandlerMapping$17(<generated>)
at com.mvc.test.WebConfig$$EnhancerBySpringCGLIB$$73e81027$$FastClassBySpringCGLIB$$ad82a9b1.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.mvc.test.WebConfig$$EnhancerBySpringCGLIB$$73e81027.resourceHandlerMapping(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 23 more
8�� 27, 2020 2:00:12 ���� org.apache.catalina.core.ContainerBase startInternal
����: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:911)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:791)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:356)
at com.mvc.test.SpringMVCApplication.start(SpringMVCApplication.java:57)
at com.mvc.test.SpringMVCApplication.main(SpringMVCApplication.java:17)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1403)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:890)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Exception in thread "main" org.apache.catalina.LifecycleException: Failed to start component [StandardServer[-1]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:356)
at com.mvc.test.SpringMVCApplication.start(SpringMVCApplication.java:57)
at com.mvc.test.SpringMVCApplication.main(SpringMVCApplication.java:17)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Tomcat]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:791)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 3 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 5 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
> Task :spring-mvc-test:SpringMVCApplication.main() FAILED
65 actionable tasks: 2 executed, 63 up-to-date
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':spring-mvc-test:SpringMVCApplication.main()'.
> Process 'command 'G:/jdk-11.0.8/bin/java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
我是根据官网配置的,但是配置文件一直报NO ServletContext set 找了半天也没发现和官网有什么区别的,没办反只能尝试debug,之后发现在初始化过程中报的错
package com.mvc.test;
import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class MyWebApplicationInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.register(WebConfig.class);
ac.refresh();//这里报错
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
官网配置
解决办法就是讲servletContext 添加到AnnotationConfigWebAppllicationContext里面
ac.setServletContext(servletContext);
修改后的代码
package com.mvc.test;
import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class MyWebApplicationInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.setServletContext(servletContext);
ac.register(WebConfig.class);
ac.refresh();
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
这样就没有问题了
14:16:19: Executing task 'SpringMVCApplication.main()'...
Starting Gradle Daemon...
Connected to the target VM, address: '127.0.0.1:61997', transport: 'socket'
Gradle Daemon started in 1 s 762 ms
> Task :spring-mvc-test:SpringMVCApplication.main()
8�� 27, 2020 2:16:40 ���� org.apache.catalina.core.StandardContext setPath
����: A context path must either be an empty string or start with a '/' and do not end with a '/'. The path [/] does not meet these criteria and has been changed to []
8�� 27, 2020 2:16:41 ���� org.apache.coyote.AbstractProtocol init
��Ϣ: Initializing ProtocolHandler ["http-nio-9090"]
8�� 27, 2020 2:16:41 ���� org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
��Ϣ: Using a shared selector for servlet write/read
8�� 27, 2020 2:16:41 ���� org.apache.catalina.core.StandardService startInternal
��Ϣ: Starting service Tomcat
8�� 27, 2020 2:16:41 ���� org.apache.catalina.core.StandardEngine startInternal
��Ϣ: Starting Servlet Engine: Apache Tomcat/8.5.5
8�� 27, 2020 2:16:41 ���� org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
��Ϣ: No global web.xml found
8�� 27, 2020 2:16:41 ���� org.apache.catalina.core.ApplicationContext log
��Ϣ: 2 Spring WebApplicationInitializers detected on classpath
-------------------------interceptor
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils (file:/G:/spring5.3.x/spring-framework/spring-core/build/libs/spring-core-5.2.3.BUILD-SNAPSHOT.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
-----------------------------------
8�� 27, 2020 2:16:45 ���� org.apache.catalina.core.ApplicationContext log
��Ϣ: Initializing Spring root WebApplicationContext
8�� 27, 2020 2:16:45 ���� org.springframework.web.context.ContextLoader initWebApplicationContext
��Ϣ: Root WebApplicationContext: initialization started
8�� 27, 2020 2:16:45 ���� org.springframework.web.context.ContextLoader initWebApplicationContext
��Ϣ: Root WebApplicationContext initialized in 63 ms
-------------------------interceptor
-----------------------------------
8�� 27, 2020 2:16:45 ���� org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
��Ϣ: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [157] milliseconds.
8�� 27, 2020 2:16:45 ���� org.apache.catalina.core.ApplicationContext log
��Ϣ: Initializing Spring DispatcherServlet 'app'
8�� 27, 2020 2:16:45 ���� org.springframework.web.servlet.FrameworkServlet initServletBean
��Ϣ: Initializing Servlet 'app'
8�� 27, 2020 2:16:45 ���� org.springframework.web.servlet.FrameworkServlet initServletBean
��Ϣ: Completed initialization in 6 ms
8�� 27, 2020 2:16:45 ���� org.apache.catalina.core.ApplicationContext log
��Ϣ: Initializing Spring DispatcherServlet 'dispatcher'
8�� 27, 2020 2:16:45 ���� org.springframework.web.servlet.FrameworkServlet initServletBean
��Ϣ: Initializing Servlet 'dispatcher'
-------------------------interceptor
-----------------------------------
8�� 27, 2020 2:16:45 ���� org.springframework.web.servlet.FrameworkServlet initServletBean
��Ϣ: Completed initialization in 62 ms
8�� 27, 2020 2:16:45 ���� org.apache.coyote.AbstractProtocol start
��Ϣ: Starting ProtocolHandler [http-nio-9090]
结束。。。。
补加 也可以这样使用
不使用WebApplicationInitializer 进行初始化
使用如下代码来实现初始化过程
package com.mvc.test;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@SuppressWarnings("rawtypes")
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
package com.mvc.test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.mvc.interceptor")
public class RootConfig {
}
package com.mvc.test;
import com.mvc.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan(value={"com.mvc.*"})
public class WebConfig extends WebMvcConfigurationSupport {
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("-----------------------------------");
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
}
@Bean
public MyInterceptor getMyInterceptor(){
return new MyInterceptor();
}
}
网友评论