Using Singleton enum in Spring MVC

2019-09-08 07:14发布

Here is my singlton class using enum:

public enum MyInstanceFactory {
    INSTANCE;    
    private SOMEOBJECT;
    private int countInitialization = 0;
    private MyInstanceFactory(){

        countInitialization++;
        System.out.println("WOW!! This has been initialized: ["+countInitialization+"] times");
        SOMEOBJECT = SOMETHING
    }

    public Session getSomeobject(){ return SOMEOBJECT; }
}

Now I am calling it like inside MVC controller

Session cqlSession = MyInstanceFactory.INSTANCE.getSomeobject();

In this way it calls constructer only first time and next and onwards it return the correct value for SOMEOBJECT.

My question is I want to do the same thing when a spring application start i.e. initializing contructor once and use **getSomeobject** multiple times.

I saw THIS SO ANSWER but here they are saying

If it finds a constructor with the right arguments, regardless of visibility, it will use reflection to set its constructor to be accessible.

Will reflection create problem for a singlton class?

1条回答
贪生不怕死
2楼-- · 2019-09-08 08:14

If you need a non-subvertible singleton class (not just a singleton bean that's shared by many other beans, but actually a singleton class where the class can only ever be instantiated once), then the enum approach is a good one. Spring won't try to instantiate the enum itself, because that really makes no sense; that would be a much more extremely broken thing to do than merely calling a private constructor.

In that case, to refer to the enum instance from Spring configuration, you do the same thing as for any other static constant; for example:

<util:constant static-field="MyInstanceFactory.INSTANCE" />
查看更多
登录 后发表回答