Using Singleton enum in Spring MVC

吃可爱长大的小学妹 提交于 2019-12-13 04:36:30

问题


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:


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" />


来源:https://stackoverflow.com/questions/21521352/using-singleton-enum-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!