Spring bean上下文刷新失败

时间:2017-12-15 14:31:16

标签: java spring spring-mvc spring-boot

我正在尝试执行下面的代码并收到一些错误。

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(AspectConfig.class);
        try{
            ctx.refresh();
        }catch(Exception e){
            ctx.close();
            throw new RuntimeException("Bean refresh failed with exception:" + e.getMessage());
        }

我的AspectConfig.java看起来像

@EnableWebMvc
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages={"ac","ab","az"})
public class AspectConfig {
     public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
}

所以这里的主要内容是我使用spring mvc调用来调用代码片段。我的春天WebServletConfiguration如下

@Override
    public void onStartup(ServletContext ctx) throws ServletException {
        AnnotationConfigWebApplicationContext webCtx = new AnnotationConfigWebApplicationContext();
        webCtx.register(AppConfig.class);
        webCtx.setServletContext(ctx);
        ServletRegistration.Dynamic servlet = ctx.addServlet("dispatcher", new DispatcherServlet(webCtx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

我的AppConfigAspectConfig几乎相同,只是它包含ViewResolver的定义。

错误是

Exception in thread "pool-1-thread-2" java.lang.RuntimeException: Bean refresh failed with exception: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 java.lang.IllegalStateException: No ServletContext set
    at framework.AnnotationProcessor.process(AnnotationProcessor.java:40)
    at runners.MultiTestRunnable.run(MultiTestRunnable.java:29)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

我已经看过下面的链接,但似乎没有任何结果。我是否无法将AnnotationContextSprings MVC

一起使用

以下是我看过的链接

Spring 5.0.0.M3 Error calling ApplicationEventListener : No ServletContext set - Exception encountered during context initialization

Error creating bean with name 'resourceHandlerMapping' defined in class path resource [EnableWebMvcConfiguration.class]

1 个答案:

答案 0 :(得分:0)

为什么你需要有两个独立的背景? 您可以在@EnableAspectJAutoProxy课程中添加AppConfig注释并尝试吗?

否则,如果您需要单独的Web和root上下文,那么我建议您尝试使用AbstractAnnotationConfigDispatcherServletInitializer类进行配置,这可以替代您的WebServletConfiguration类。 有关详细信息,请参阅link