简体   繁体   中英

Use external object in Jersey GET response

I am developing a rest API service with Jersey and Jetty. It is pretty simple and I have a number of endpoints like this:

@GET
@Path("/username/{username : [a-zA-Z][a-zA-Z_0-9]}")
@Produces(MediaType.TEXT_PLAIN)
public String getUsername(@Context UriInfo uriInfo, String content) {
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    String nameParam = queryParams.getFirst("name");
    //Dataset<Row> df = GetDataFrame.getDF();
    return "test";
}

in the getUserName method, I need to use an object which I have created in the main class. The main class is at the moment like this:

SourceHandler source = new SparkHandler(inputSource);
    source.loadIntoMemory();

    Server server = new Server(8080);
    ServletContextHandler ctx =
            new ServletContextHandler(ServletContextHandler.NO_SESSIONS);

    ctx.setContextPath("/");
    server.setHandler(ctx);

    ServletHolder serHol = ctx.addServlet(ServletContainer.class, "/rest/*");
    serHol.setInitOrder(1);
    serHol.setInitParameter("jersey.config.server.provider.packages",
            "com.ed7.res");

I would like to use the source object in the GET responses. Is there a best practice to do that in Jersey? Otherwise, I would create another class with a static field/static method that returns that particular object.

You can use HK2 DI. What you can do to configure it is create a standalone ServiceLocator and set that locator to be the parent locator of the app, using a Jersey property .

public static void main(String... args) {
    SourceHandler source = new SparkHandler(inputSource);

    ServiceLocator locator = ServiceLocatorUtilities.bind(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(source).to(SourceHandler.class);
        }
    });

    ServletHolder serHol = ctx.addServlet(ServletContainer.class, "/rest/*");
    serHol.setInitParameter(ServletProperties.SERVICE_LOCATOR, locator);
}

Then you can just @Inject the SourceHandler anywhere you need it

@Path("whatever")
public class Resource {

    @Inject
    private SourceHandler sourceHandler;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM