如何在Java REST Web服务中注入应用程序范围的Bean

3

我需要在ContextCacheRefresh web服务上注入initApplicationContext bean,但是不成功,initApplicationContext的值总是null。请问有人知道如何解决吗?

@ManagedBean(name = "initApplicationContext", eager = true)
@ApplicationScoped
   public class InitApplicationContext {
             .......................
               }

和网络服务

  @Path("/serviceContext")
  public class ContextCacheRefresh  {

   @ManagedProperty(value = "#{initApplicationContext}")
    private  InitApplicationContext initApplicationContext;

  @GET
  @Path("/refreshContext")

 public Response refreshUserListOn(@QueryParam("param") String param
  ) { ......

这是一个JSF应用程序吗?如果不是,您应该使用@Inject - kolossus
是的,它是JSF应用程序。 - Saimir
不是很好:您正在尝试将JSF资源注入到非JSF上下文中;这是行不通的。 - kolossus
使用@Named注解替代@ManagedBean,并使用@Inject将其注入到您的Restful服务中。管理Bean仅是JSF页面的控制器。 - Everv0id
1个回答

2

您无法使用@ManagedProperty让JSF将资源注入非JSF上下文。您的选择是:

  1. Convert your managed bean to use CDI annotations (@Named to declare the managed bean and @Inject instead of the JSF annotations you're working with now.

  2. Just pull the bean from the plain servlet context using the following:

    //inject the servlet context
    @javax.ws.rs.core.Context 
    ServletContext servletContext
    
    public InitApplicationContext getInitContext(){
        return (InitApplicationContext)servletContext.getAttribute("initApplicationContext");
    }
    
你的工作似乎有些不可靠。为什么你的Web应用程序会涉及到RESTful端点呢?

非常感谢,它有效了! - Saimir
我正在开发分离的多模块Web应用程序,所有模块都使用相同的数据库实例。我必须将一个模块中的更改反映到其他模块中,因此我选择使用Web服务。 - Saimir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接