【发布时间】: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你可以使用依赖注入。