Я пытаюсь использовать servletcontext.getRealPath в моем классе Util для загрузки файлового ресурса (не является частью модульного тестирования), но он не работает.Не могу назначить ServletContext spring 3
Я пытался как использовать "реализует ServletContextAware":
@Component
public class Utils implements ServletContextAware{
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
System.out.println("**** "+servletContext);
}
}
Какие броски NPE поскольку ServletContext не назначен весной.
И @Autowired маршрут:
@Component
public class Utils{
@Autowired
private ServletContext servletContext;
Который бросает 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)}
Я добавляю в мой код инициализации в случае, если я делаю что-то неправильно, который предотвращает Весну для ввода правильного компонента.
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 класс с контекстом сервлета.
Я рассмотрел предложенные ответы: here и here и он не работал.
Вам нужно объявить этот компонент в контексте, который имеет доступ к 'ServletContext'. Кажется, вы этого не делаете. –
@SotiriosDelimanolis - Я не уверен, что понимаю, что это значит или как это сделать :). Можете ли вы привести пример или ссылку? – special0ne
Попробуйте вызвать 'setServletContext()' в вашем 'rootContext' явно. Я не уверен, что он вызывается, когда контекст передается конструктору 'ContextLoaderListener'. – axtavt