【问题标题】:SpringContext in REST serviceREST 服务中的 Spring 上下文
【发布时间】:2017-05-01 08:39:24
【问题描述】:

一般我们在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 这是解释here

【问题讨论】:

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

标签: java spring rest servlets


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 2017-10-31
    • 2017-11-27
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    相关资源
    最近更新 更多