Frage

@Path("/test")
public class MyClass {

  @GET
  public Response response() {
    // Generating some expensive object here.
  }

Right now I load the data into arrays etc inside the "response" function, but I want to do it before the query is even made. This way, I want to avoid reloading the data every time a a query is made. How do I achieve this?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top