2015-09-05 24 views
2

我有以下类:泽西2化妆类/对象持续整个应用程序

package com.crawler.c_api.rest; 

import com.crawler.c_api.provider.ResponseCorsFilter; 
import java.util.logging.Logger; 

import org.glassfish.jersey.filter.LoggingFilter; 
import org.glassfish.jersey.server.ResourceConfig; 
import org.glassfish.jersey.server.ServerProperties; 

public class ApplicationResource extends ResourceConfig { 

    private static final Logger LOGGER = null; 

    public ServiceXYZ pipeline; 

    public ApplicationResource() { 
     System.out.println("iansdiansdasdasds"); 
     // Register resources and providers using package-scanning. 
     packages("com.crawler.c_api"); 

     // Register my custom provider - not needed if it's in my.package. 
     register(ResponseCorsFilter.class); 

     pipeline=new ServiceXYZ(); 

     //Register stanford 
     /*Properties props = new Properties(); 
     props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref"); 
     pipeline = new StanfordCoreNLP(props);*/ 

     // Register an instance of LoggingFilter. 
     register(new LoggingFilter(LOGGER, true)); 

     // Enable Tracing support. 
     property(ServerProperties.TRACING, "ALL"); 
    } 
} 

我想使可变管道持续整个应用程序,所以我可以一次初始化服务,并在所有其他使用它类。

我该怎么做?

回答

2

看看Custom Injection and Lifecycle Management。它会给你一些关于如何使用Jersey进行依赖注入的想法。举个例子,你首先需要将服务绑定到注入框架

public ApplicationResource() { 
    ... 
    register(new AbstractBinder(){ 
     @Override 
     public void configure() { 
      bind(pipeline).to(ServiceXYZ.class); 
     } 
    }); 
} 

然后,你可以注入ServiceXYZ到您的任何资源类或供应商(如过滤器)。

@Path("..") 
public class Resource { 
    @Inject 
    ServiceXYZ pipeline; 

    @GET 
    public Response get() { 
     pipeline.doSomething(); 
    } 
} 

上述配置将单个(单例)实例绑定到框架。

额外:-)不是为你的用例,而是说例如你想为每个请求创建一个新的服务实例。然后你需要把它放在请求范围内。

bind(ServiceXYZ.class).to(ServiceXYZ.class).in(RequestScoped.class); 

请注意区别bind。第一个使用实例,而第二个使用该实例。没有办法在请求范围内以这种方式绑定实例,所以如果您需要特殊的初始化,那么您需要使用Factory。你可以在我上面提供的链接中看到一个例子

+0

再次感谢:)似乎更复杂,然后我想。稍后会看看! –

+0

其实并没有那么复杂。您可以复制并粘贴第一个代码片段,然后只需将注释添加到您需要的地方 –

+0

好极了!有用。没有不复杂;) –