比较来自世界各地的卖家的域名和 IT 服务价格

失败 Autowire ServletContext

我是新的b。 Spring, 我正在尝试使用注释 @Autowire 为了 ServletContext 使用我的类属性:


@Controller
public class ServicesImpl implements Services{

@Autowired
ServletContext context;


我在我的班上定义了这个班级的鲍勃 dispatcher-servlet.xml:


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


但是当我尝试运行测试时 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 是自动的。 spring... 我怎么解决这个问题?

谢!

EDIT: 我想使用 servletContext 调用方法 getRealPath//. 有替代方案吗?
已邀请:

快网

赞同来自:

实现界面 ServletContextAware, 和 Spring 为您介绍它


@Controller
public class ServicesImpl implements Services, ServletContextAware{


private ServletContext context;

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

窦买办

赞同来自:

你可能想看看 MockServletContext
http://static.springsource.org ... .html
可用于模块化测试。

卫东

赞同来自:

ServletContext

不是鲍勃 Spring, 因此,如果您不实施,则无法介绍
http://static.springsource.org ... .html
.

如果有人在模块或图层中思考,则Servlet的上下文不应该在外面使用 web module/layer. 我想你
ServicesImpl

它是企业或服务级别的一部分。

如果您提供了更多的背景,我们可以提供最佳选择。

要回复问题请先登录注册