What corresponds to asEagerSingleton in HK2 in Jersey 2?

Viewed 2527

I am developing a REST API using Jersey 2 and I need some of my classes to be instantiated on start up and not just when some resource request triggers it.

So what I am asking is: how do I achieve that an instance of SomethingImpl defined below here is created on server start up and not just when someone hits the something resource? In Guice I would use .asEagerSingleton().

Application:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        register(new AbstractBinder() {
            @Override
            protected void configure() {
                bind(" else").to(String.class);
                bind(SomethingImpl.class).to(Something.class).in(Singleton.class);
            }
        });

        register(SomeResource.class);
    }
}

Something:

public interface Something {
   String something();
}

public class SomethingImpl implements Something {
    @Inject
    public SomethingImpl(final String something) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println(something() + something);

                    try {
                        Thread.sleep(4000);

                    } catch (final InterruptedException e) {
                        break;
                    }
                }
            }
        }).start();
    }

    @Override
    public String something() {
        return "Something";
    }
}

Some resource:

@Path("/")
public class SomeResource {
    private final Something something;

    @Inject
    public SomeResource(final Something something) {
        this.something = something;
    }

    @GET
    @Path("something")
    public String something() {
        return something.something();
    }
}
3 Answers
Related