users@jersey.java.net

[Jersey] Re: Regsitering singletons

From: Maarten Boekhold <boekhold_at_gmx.com>
Date: Wed, 09 Mar 2016 18:56:56 +0400

Is something like this what you are looking for?

http://stackoverflow.com/a/28018490/1023458

Maarten


On 9 March 2016 17:27:17 ax487 <ax487_at_gmx.de> wrote:

> 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