mardi 12 juillet 2016

A good way to implement Singleton pattern with Spring

I want to implement Singleton pattern in context of Spring application. So even my singleton object will be created by spring.

To do that:

I put a class that implements ApplicationContextAware to get beans from spring context:

public class AppContext implements ApplicationContextAware
{

  /**
   * Private instance of the AppContext.
   */
  private static AppContext _instance;

  /**
   * @return the instance of AppContext
   */
  public static AppContext getInstance()
  {

    return AppContext._instance;
  }

  /**
   * Instance of the ApplicationContext.
   */
  private ApplicationContext _applicationContext;

  /**
   * Constructor (should never be call from the code).
   */
  public AppContext()
  {
    if (AppContext._instance != null)
    {
      throw (new java.lang.RuntimeException(Messages.getString("AppContext.singleton_already_exists_msg"))); //$NON-NLS-1$
    }
    AppContext._instance = this;
  }

  /**
   * Get an instance of a class define in the ApplicationContext.
   * 
   * @param name_p
   *          the Bean's identifier in the ApplicationContext
   * @param <T>
   *          the type of the returned bean
   * @return An instance of the class
   */
  @SuppressWarnings("unchecked")
  public <T> T getBean(String name_p)
  {

    return (T) _applicationContext.getBean(name_p);
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext_p) throws BeansException
  {
    _applicationContext = applicationContext_p;
  }
}

My singleton class:

    public class MySingleton {

    private static MySingleton instance= null; 
    public static final String BEAN_ID = "mySingletonInstanceId"; 

    private MySingleton(){}


    public static MySingleton getInstance(){
       return AppContext.getInstance().getBean(mySingletonInstanceId.BEAN_ID);
    }
   }

My application.xml file:

    <beans xmlns="http://ift.tt/GArMu6"
           xmlns:xsi="http://ift.tt/ra1lAU" xmlns:jaxws="http://ift.tt/1ej3bYY"
           xmlns:cxf="http://ift.tt/1iXPlPh" xmlns:jaxrs="http://ift.tt/1kNxCZA"
           xsi:schemaLocation="
    http://ift.tt/GArMu6 
    http://ift.tt/1jdM0fG
    http://ift.tt/1ej3bYY http://ift.tt/1ej3cfe
    http://ift.tt/1kNxCZA
    http://ift.tt/1iXPm5B
    http://ift.tt/1iXPlPh http://ift.tt/1iXPj9S">

    <!--some code-->

        <bean id="idAppContext" class="com.AppContext" />
        <bean id="mySingletonInstanceId" class="com.MySingleton"/>

    <!--some code-->

    </beans>

Do you think that my code is good ?

instance field is no longer necessary?

Considering that Spring will manage every everything, getInstance() has only to return singleton instance created by spring ?

Aucun commentaire:

Enregistrer un commentaire