This depends on your framework. Are you using the reference implementation Jersey? Jersey comes bundled with HK2 automatically. Then you could add
@Path("/test")
public class MyClass {
@Inject
private MyState stateful;
// here comes your code...
}
to your resource. Of course, you would still need to configure what to inject into this field. With HK2, you use an AbstractBinder
for this purpose:
class MyBinder extends AbstractBinder {
private final MyState stateful;
public MyBinder (MyState stateful) {
this.stateful = stateful;
}
@Override
protected void configure() {
bind(stateful).to(MyState.class);
}
}
Finally, you need to add this binder on the application's setup. For this purpose, JAX-RS Application
object can be queried for singletons. Simply add the required instance to the application such that it is returned by Application#getSingletons
as here:
class MyJaxRSApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
return Collections.singletonSet(MyClass.class);
}
@Override
public Set<Object> getSingletons() {
return Collections.singletonSet(new MyBinder(new MyStateImpl()));
}
}
You can now run your application where MyStateImpl
is always injected into MyClass
.