Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What corresponds to asEagerSingleton in HK2 in Jersey 2?

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();
    }
}
like image 701
Stine Avatar asked Dec 20 '13 22:12

Stine


1 Answers

In a later release of hk2 than is integrated with Jersey (but which will be integrated soon) you can have services that are marked @Immediate. These basically get started as soon as they are added to hk2. However, in order to make it work you will have to add the Immediate context to the system (e.g. https://hk2.java.net/2.2.0-b27/apidocs/org/glassfish/hk2/utilities/ServiceLocatorUtilities.html#enableImmediateScope%28org.glassfish.hk2.api.ServiceLocator%29)

It would be a good idea to lobby with the Jersey team to have this scope/context pair enabled by default (they already enable things like PerThread scope)

I have created this issue: https://java.net/jira/browse/JERSEY-2291 to request that Jersey enable @Immediate services by default

like image 187
jwells131313 Avatar answered Oct 04 '22 21:10

jwells131313