Java 无法分配ServletContext spring 3
我试图在Util类中使用servletcontext.getRealPath来加载文件资源(不是单元测试的一部分),但它不起作用 我尝试使用“implements ServletContextAware”: 它抛出NPE,因为servletcontext不是由spring分配的 以及@Autowired路由:Java 无法分配ServletContext spring 3,java,spring,spring-mvc,autowired,Java,Spring,Spring Mvc,Autowired,我试图在Util类中使用servletcontext.getRealPath来加载文件资源(不是单元测试的一部分),但它不起作用 我尝试使用“implements ServletContextAware”: 它抛出NPE,因为servletcontext不是由spring分配的 以及@Autowired路由: @Component public class Utils{ @Autowired private ServletContext servletContext; 在启动
@Component
public class Utils{
@Autowired
private ServletContext servletContext;
在启动tomcat时引发NoSuchBeanDefinitionException:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.ServletContext] found for dependency: expected at le
ast 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我正在添加我的初始化代码,以防我做了一些错误,阻止Spring注入正确的bean
public class WebAppInitializer implements WebApplicationInitializer {
private static Logger LOG = LoggerFactory.getLogger(WebAppInitializer.class);
@Override
public void onStartup(ServletContext servletContext) {
WebApplicationContext rootContext = createRootContext(servletContext);
configureSpringMvc(servletContext, rootContext);
FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", CORSFilter.class);
corsFilter.addMappingForUrlPatterns(null, false, "/*");
// configureSpringSecurity(servletContext, rootContext);
}
private WebApplicationContext createRootContext(ServletContext servletContext) {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// rootContext.register(CoreConfig.class, SecurityConfig.class);
rootContext.register(CoreConfig.class);
rootContext.refresh();
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("defaultHtmlEscape", "true");
return rootContext;
}
CoreConfig.class:
@Configuration
public class CoreConfig {
@Bean
public CaptionFixture createCaptionFixture() {
return new CaptionFixture();
}
@Bean
public Utils createUtils () {
return new Utils();
}
}
Utils是具有servlet上下文的类
我已经看过了建议的答案:但它不起作用 问题在于您调用的是
refresh()
,而没有注册ServletContext
,因此在初始化bean时没有可用的
摆脱这个电话
rootContext.refresh();
ContextLoaderListener
将负责调用refresh()
。解释了当作为参数传递的ApplicationContext
未刷新时发生的情况。您需要在可以访问ServletContext
的上下文中声明此bean。你似乎没有那样做。@SotiriosDelimanolis-我不知道我明白这是什么意思或者怎么做:)。您可以提供一个示例或链接吗?请尝试显式调用rootContext
上的setServletContext()
。我不确定在将上下文传递给ContextLoaderListener
的构造函数时是否会调用它。有趣的是,我采用了Spring的REST教程中的配置。()-谢谢
rootContext.refresh();