Java REST服务中的SpringContext

Java REST服务中的SpringContext,java,spring,rest,servlets,Java,Spring,Rest,Servlets,通常,我们在servlet中使用Spring上下文,如下所示 WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); SomeBean someBean = (SomeBean) ctx.getBean("someBean"); 但在REST中,使用注释声明的服务实际上不是servlet。所以我们没有得到getSer

通常,我们在servlet中使用Spring上下文,如下所示

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
但在REST中,使用注释声明的服务实际上不是servlet。所以我们没有得到getServletContext()

如何处理这件事

回答 1) 通过将上下文作为参数传递给方法

@GET
@Path("/create")
@Produces(MediaType.TEXT_PLAIN)
public String createCustomer(@Context ServletContext servletContext){
2) 另一个解决方案是使用ApplicationContextAware
这将被解释为

以获取您可以让您的服务实现的应用程序上下文。然后,在创建服务时,Spring将调用
setApplicationContext
方法为您提供应用程序上下文。在该方法中,您可以存储所提供的上下文供以后使用。

您不应该这样做,应该使用依赖项注入。当您进行查找时,通常需要后退一步并重新思考。@M.Deinum您的意思是使用我上面提到的ApplicationContextAware编辑吗?不。。。我是说依赖注入。您不应该直接使用
ApplicationContext
来获取bean。您应该将它们注入@M.Deinum,但我的服务类的对象不是由REST框架创建的,对吗?我不是通过getBean创建它们的。那么我如何使用依赖注入呢。请您写下详细的答案或给出解释的URL。如果您可以使用
ApplicationContextAware
您可以使用依赖注入。