For simplifying our web services I'd like to introduce a custom MyObj class using the Jersey framework in version 2.34 and want to inject the created instances via the @Context annotation.
I have two questions:
Assuming a web service method @GET test(@Context MyObj obj), how can I control when instances of MyObj are created in respect to the execution of existing servlet request filters?
To create instances of MyObj, I already have a working example based on HK2's Factory's (see below). Since I observed that my factory class gets instantiated twice, and Jersey 2.26+ recomments to use the newer approach based on Supplier's, I tried to convert my example. Unfortunately, configure() won't be called in the provided Binder implements Supplier class, and thus, no objects get created. How can I get this working? (Btw., In both cases, Binder and BinderHK are registered via jersey.config.server.provider.classnames in my web.xml.)
Thank you for any help.
Working HK2 Factory example:
public class MyObjHK {}
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.process.internal.RequestScoped;
public class BinderHK
extends AbstractBinder {
@Override protected void configure() {
bindFactory(MyObjFactoryHK.class).to(MyObjHK.class).in(RequestScoped.class);
}
}
import org.glassfish.hk2.api.Factory;
public class MyObjFactoryHK
implements Factory<MyObjHK> {
@Override public MyObjHK provide() {return new MyObjHK();} // ok
@Override public void dispose(MyObjHK instance) {};
}
public class API_HK2 {
@GET
public static Response myobjhk(@Context MyObjHK obj) {
System.out.println("called hk, obj="+obj); // ok
return Response.ok().build();
}
}
Not working Supplier example:
public class MyObj {}
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.process.internal.RequestScoped;
public class Binder
extends AbstractBinder {
@Override protected void configure() { // not called ???
bindFactory(MyObjFactory.class).to(MyObj.class).in(RequestScoped.class);
}
}
import java.util.function.Supplier;
public class MyObjFactory
implements Supplier<MyObj> {
@Override public MyObj get() {return new MyObj();}
}
public class API {
@GET
public static Response myobj(@Context MyObj obj) {
System.out.println("called, obj="+obj); // null ???
return Response.ok().build();
}
}