Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring Can';自动连线服务上下文_Spring - Fatal编程技术网

Spring Can';自动连线服务上下文

Spring Can';自动连线服务上下文,spring,Spring,我是Spring新手,我正在尝试将@Autowire注释用于ServletContext和我的class属性: @Controller public class ServicesImpl implements Services{ @Autowired ServletContext context; 我在dispatcher-servlet.xml中定义了此类的bean: <bean id="services" class="com.xxx.yyy.ServicesImp

我是Spring新手,我正在尝试将@Autowire注释用于ServletContext和我的class属性:

@Controller
public class ServicesImpl implements Services{

    @Autowired
    ServletContext context;
我在dispatcher-servlet.xml中定义了此类的bean:

<bean id="services" class="com.xxx.yyy.ServicesImpl" />
我认为ServletContext注入在spring中是自动的。。。我怎样才能解决这个问题

谢谢


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

ServletContext
不是Springbean,因此,除非您实现,否则它不能被注入

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


如果您提供多一点上下文,我们可能会建议更好的替代方案。

您可能会想看看哪些可以用于单元测试。

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

@Controller
public class ServicesImpl implements Services, ServletContextAware{


private ServletContext context;

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

你好,Marcel,我正在尝试使用它,以便调用getRealPath方法来获取根目录。除此之外,我还可以如何做到这一点?谢谢但是我如何使用它呢?我应该像这样在test-context.xml中定义bean吗:
?我定义了它,不再出现任何错误,但是上下文变量为null…如果使用下面的代码,将为您创建一个MockServletContext,您将能够在ServletContext字段上使用@Autowired。@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration(classes={WebSpringConfiguration.class})是的,如果它来自JUNit,你应该使用MockServletContext抱歉删除帖子,我在test-context.xml中定义了MockServletContext bean,但变量仍然为null…你正在加载test-context.xml吗,在我的测试类中,我使用了
@ContextConfiguration(“test context.xml”)
注释,是吗?在Junit中,您只需使用@WebAppConfiguration()注释测试类,然后将注入servletcontext,您也可以删除servletcontext属性上的自动连接。
@Controller
public class ServicesImpl implements Services, ServletContextAware{


private ServletContext context;

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