users@jersey.java.net

[Jersey] Regsitering singletons

From: ax487 <ax487_at_gmx.de>
Date: Wed, 9 Mar 2016 14:26:07 +0100

Hello all,

I am wondering about the correct way to register singletons in a
ResourceConfig. I have a class which has no trivial constructor so any
attempt to create a new instance using reflection will fail.

I did like the idea of using `registerInstance(new
SingletonExample(args))`. I tried this out with a singleton subclassing
`ApplicationEventListener`. In this case the singleton was used and
received events. However, as soon as I tried to `_at_Inject` the
`SingletonExample` into some resource I immediately got an exception.

I saw a related thread here:

https://stackoverflow.com/questions/23304404/trouble-creating-a-simple-singleton-class-in-jersey-2-using-built-in-jersey-depe

The solution seems to be to use a factory like this:

  register(new AbstractBinder() {
    @Override
    protected void configure() {
      bindFactory(new SingletonFactory(new SingeltonExample(args)))
        .to(SingletonExample.class)
        .in(Singleton.class);
    }
  });

Where the `SingletonFactory` implements `Factory<SingletonExample>` and
always yields the same instance. This way I can inject the singleton and
everything works as it should. However, this approach introduces a lot
of overhead and I would really rather keep things simple.

I noticed that it is not possible to bind instances like this:

  registerInstance(new SingletonExample(args))
    .to(SingletonExample.class)

Am I missing something or is there really no easy way to register
singletons?

ax487