Here I have a singleton, that I whant to inject to my application
@Singleton
@Path("singleton-bean")
public class MyContext {
private MyContext() {
instances++;
}
private static MyContext instance;
public static MyContext getInstance(){
if (instance == null)
instance = new MyContext();
return instance;
}
public static int instances = 0;
}
Here's how I register it:
@ApplicationPath("webresources")
public class ApplicationConfig extends Application {
@Override
public Set<Object> getSingletons() {
final Set<Object> singletons = new HashSet<>();
singletons.add(MyContext.getInstance());
return singletons;
}
//.....
Finally, I print the nuber of singletons in request:
@Path("foo")
public class Foo {
@Inject
public MyContext message;
@GET
public String index() throws UnknownHostException {
return String.format("%s number of instances: %s", message, MyContext.instances);
}
It returns two instances. I understand that Jersey uses reflections to access private constructor and create another instance. Why is this happening and how do I prevent this?