spring 无法自动装配 ServletContext
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14895728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't Autowire ServletContext
提问by qxlab
I'm new with Spring, and I'm trying to use the @Autowire annotation for the ServletContext with my class attribute:
我是 Spring 的新手,我正在尝试将 @Autowire 注释用于 ServletContext 和我的类属性:
@Controller
public class ServicesImpl implements Services{
@Autowired
ServletContext context;
I defined the bean for this class in my dispatcher-servlet.xml:
我在 dispatcher-servlet.xml 中为这个类定义了 bean:
<bean id="services" class="com.xxx.yyy.ServicesImpl" />
But when I try to run a JUnit test it gives the following error:
但是当我尝试运行 JUnit 测试时,它会出现以下错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
I thought that the ServletContext injection was automatic with spring... How can I solve this?
我认为 ServletContext 注入是用 spring 自动的......我该如何解决这个问题?
Thanks!
谢谢!
EDIT: I want to use the servletContext to call the getRealPath() method. Is there any alternative?
编辑:我想使用 servletContext 来调用 getRealPath() 方法。有什么替代方法吗?
回答by ccheneson
Implement the ServletContextAwareinterface and Spring will inject it for you
实现ServletContextAware接口,Spring 会为你注入
@Controller
public class ServicesImpl implements Services, ServletContextAware{
private ServletContext context;
public void setServletContext(ServletContext servletContext) {
this.context = servletContext;
}
回答by tstorms
You'll probably want to take a look at MockServletContextwhich can be used in unit tests.
您可能想看看可用于单元测试的MockServletContext。
回答by Marcel St?r
ServletContextis not a Spring bean and it can, therefore, not be injected unless you implement ServletContextAware.
ServletContext不是 Spring bean,因此,除非您实现ServletContextAware.
If one thinks in modules or layers then the servlet context shouldn't be available outside the web module/layer. I suppose your ServicesImplforms part of the business or service layer.
如果在模块或层中思考,那么 servlet 上下文不应该在 web 模块/层之外可用。我想你的ServicesImpl形式是业务或服务层的一部分。
If you gave a little more context we might be able to suggest better alternatives.
如果您提供更多背景信息,我们可能会提出更好的替代方案。

