我正在尝试执行下面的代码并收到一些错误。
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("/");
}
我的AppConfig
与AspectConfig
几乎相同,只是它包含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)
我已经看过下面的链接,但似乎没有任何结果。我是否无法将AnnotationContext
与Springs MVC
以下是我看过的链接
答案 0 :(得分:0)
为什么你需要有两个独立的背景?
您可以在@EnableAspectJAutoProxy
课程中添加AppConfig
注释并尝试吗?
否则,如果您需要单独的Web和root上下文,那么我建议您尝试使用AbstractAnnotationConfigDispatcherServletInitializer
类进行配置,这可以替代您的WebServletConfiguration
类。
有关详细信息,请参阅link。