Jersey 2: how can I set values in an injectable class, so they are available when that class is injected into an API resource?

I have moved from Jersey 1.19 to: Jersey 2.41 with HK2 and Jetty 10.0.20. Java version is 17.

Note: this is not my area of expertise – I managed to get the REST server working for v1 and I need to do the same for v2.

In my v1 code, in the class that starts the HTTPServer, I set values in the class to be injected (ISyslogServerParm), as follows:

Injector injector = Guice.createInjector(new SyslogAPIModule());
ISyslogServerParms serverParms = injector.getInstance(ISyslogServerParms.class);
serverParms.setEventTrackers(eventTrackers);

I have spent all day trying to find out how to do this with Jersey 2, without success.
I have got to the point of using the ResourceConfig, but I’m basically lost.

ISyslogServerParms gets injected OK. What I can’t find a way to do, is to invoke setEventtrackers()… somewhere.

The API:

package com.w3p.api;
@Path("njams")
public class MyMessageAPI { 
    @Inject
    private ISyslogServerParms syslogServerParms;

    @POST
    @Path("syslog")
    @Consumes(MediaType.TEXT_XML)
    public Response handleSysLogMsg(String syslogData) {
    ...
    }

The REST server:

    public class MyRestServer {

    private final List<String> eventTrackers; 
    
    public MyRestServer(List<String> eventTrackers) {           
        this.eventTrackers = eventTrackers;
    }

    public void run() {
        ApplicationConfig config = new ApplicationConfig(eventTrackers);
        ...
    }
}

The ResourceConfig

public class ApplicationConfig extends ResourceConfig{  
    @Inject
    public ApplicationConfig(List<String> eventTrackers) {List<String> eventTrackers) {
       packages("com.w3p.api");       
       register(new ApplicationBinder());
       ServiceLocator locator = ServiceLocatorFactory.getInstance().create("MyMessageAPI");
       ISyslogServerParms parms = locator.getService(ISyslogServerParms.class); 
       parms.setEventTrackers(eventTrackers);
    }

The above use of a ServiceLocator is guesswork based on replies and documentation. I didn’t expect parms to be magically resolved, and it is indeed null.

I would be really grateful if someone could provide me with guidance on how I should go about solving this.

Leave a Comment