无法自动装配ServletContext

时间:2013-02-15 13:21:57

标签: spring

我是Spring的新手,我正在尝试使用带有class属性的ServletContext的@Autowire注释:

@Controller
public class ServicesImpl implements Services{

    @Autowired
    ServletContext context;

我在dispatcher-servlet.xml中为这个类定义了bean:

<bean id="services" class="com.xxx.yyy.ServicesImpl" />

但是当我尝试运行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)}

我认为ServletContext注入是自动弹簧...我该如何解决这个问题?

谢谢!

编辑:我想使用servletContext来调用getRealPath()方法。还有其他选择吗?

3 个答案:

答案 0 :(得分:21)

实现ServletContextAware接口,Spring将为您注入

@Controller
public class ServicesImpl implements Services, ServletContextAware{


private ServletContext context;

public void setServletContext(ServletContext servletContext) {
     this.context = servletContext;
}

答案 1 :(得分:10)

您可能希望查看可用于单元测试的MockServletContext

答案 2 :(得分:3)

ServletContext不是Spring bean,因此,除非您实现ServletContextAware,否则不能注入它。

如果在模块或层中思考,那么servlet上下文不应该在Web模块/层之外可用。我认为您的ServicesImpl构成了业务或服务层的一部分。

如果您提供更多背景信息,我们可以提出更好的选择。

相关问题