我正在尝试在我的Util类中使用servletcontext.getRealPath来加载文件资源(不是单元测试的一部分),但它不起作用。
我试过两个都使用“implements ServletContextAware”:
@Component
public class Utils implements ServletContextAware{
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
System.out.println("**** "+servletContext);
}
}
由于servletcontext未由spring分配,因此抛出NPE。
和@Autowired路线:
@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上下文的类。
答案 0 :(得分:3)
问题是您在没有注册refresh()
的情况下调用ServletContext
,因此在初始化bean时没有可用的。
摆脱这个电话
rootContext.refresh();
ContextLoaderListener
将负责调用refresh()
。 constructor javadoc解释了当作为参数传递的ApplicationContext
未被刷新时会发生什么。