【问题标题】:Jersey 2 make class/object persist throughout the appJersey 2 使类/对象在整个应用程序中持续存在
【发布时间】:2015-12-01 15:45:53
【问题描述】:

我有以下课程:

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");
    }
}

我想让变量管道在整个应用程序中持续存在,这样我就可以初始化服务一次并在每个其他类中使用它。

我该怎么做?

【问题讨论】:

    标签: java rest jersey jersey-2.0


    【解决方案1】:

    看看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();
        }
    }
    

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

    额外 :-) 不是针对您的用例,而是说您希望为每个请求创建一个新的服务实例。然后,您需要将其放入请求范围内。

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

    注意bind 的区别。第一个使用实例,而第二个使用类。无法在请求范围内以这种方式绑定实例,因此如果需要特殊初始化,则需要使用Factory。您可以在我上面提供的链接中看到一个示例

    【讨论】:

    • 再次感谢 :) 似乎比我想象的要复杂。以后会看的!
    • 其实没那么复杂。您可以复制并粘贴第一个 sn-p,然后将带有注释的服务注入您需要的地方
    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2013-06-16
    • 2017-01-20
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多