Search code examples
javarestjerseyjersey-2.0

Jersey 2 make class/object persist throughout the app


I have following class:

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

I would like to make the variable pipeline persist throughout the app so i can initialize the service once and use it in every other class.

How can i do that?


Solution

  • Take a look at Custom Injection and Lifecycle Management. It will give you some idea for how to work with dependency injection with Jersey. As an example, you first need to bind the service to the injection framework

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

    Then you can just inject ServiceXYZ into any of your resource classes or providers (like filters).

    @Path("..")
    public class Resource { 
        @Inject
        ServiceXYZ pipeline;
    
        @GET
        public Response get() {
            pipeline.doSomething();
        }
    }
    

    The above configuration binds the single (singleton) instance to the framework.

    Extra :-) Not for your use case, but say for instance you wanted a new instance of the service to be created for each request. You would then need to put it in a request scope.

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

    Notice the difference in the bind. The first one uses the instance, while the second one uses the class. There is no way to bind the instance this way in a request scope, so if you need special initialization, then you would need to use a Factory. You can see an example in the link I provided above