如何在 rest web 服务上注入应用程序范围 bean java

how to inject Application scope bean on rest web service java

我必须在 ContextCacheRefresh Web 服务上注入 initApplicationContext bean,但没有成功,initApplicationContext 值始终为空。有人知道如何处理吗?

@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
  ) { ......

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

  1. 将您的托管 bean 转换为使用 CDI 注释(@Named 声明托管 bean 和 @Inject 而不是您现在使用的 JSF 注释。

  2. 只需使用以下命令从普通 servlet 上下文中提取 bean:

    //inject the servlet context
    @javax.ws.rs.core.Context 
    ServletContext servletContext
    
    public InitApplicationContext getInitContext(){
        return (InitApplicationContext)servletContext.getAttribute("initApplicationContext");
    }
    

我觉得你的工作有点不靠谱。为什么您的 Web 应用程序首先关注您的 RESTful 端点?