无法自动装配ServletContext

qxl*_*lab 19 spring

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

@Controller
public class ServicesImpl implements Services{

    @Autowired
    ServletContext context;
Run Code Online (Sandbox Code Playgroud)

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

<bean id="services" class="com.xxx.yyy.ServicesImpl" />
Run Code Online (Sandbox Code Playgroud)

但是当我尝试运行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)}
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

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

cch*_*son 23

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

@Controller
public class ServicesImpl implements Services, ServletContextAware{


private ServletContext context;

public void setServletContext(ServletContext servletContext) {
     this.context = servletContext;
}
Run Code Online (Sandbox Code Playgroud)

  • 在Junit中,您只需使用@WebAppConfiguration(http://docs.spring.io/spring/docs/3.2.8.RELEASE/javadoc-api/org/springframework/test/context/web/WebAppConfiguration)注释测试类. html)和servletcontext将被注入,你也可以删除servletContext属性上的自动装配. (4认同)

tst*_*rms 10

你可能想看看可以在单元测试中使用的MockServletContext.