2016-07-12 2 views
0

Я хочу реализовать шаблон Singleton в контексте приложения Spring. Так что даже мой одиночный объект будет создан весной.Хороший способ реализации шаблона Singleton с Spring

Чтобы сделать это:

Я поставил класс, который реализует ApplicationContextAware, чтобы получить бобы из пружинной контекста:

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; 
    } 
} 

Мой синглтон класс:

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); 
    } 
    } 

Мой application.xml файл:

<beans xmlns="http://www.springframework.org/schema/beans" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" 
      xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxrs="http://cxf.apache.org/jaxrs" 
      xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd 
    http://cxf.apache.org/jaxrs 
    http://cxf.apache.org/schemas/jaxrs.xsd 
    http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"> 

    <!--some code--> 

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

    <!--some code--> 

    </beans> 

Считаете ли вы, что мой код хорош?

экземпляры больше не нужно поле?

Учитывая, что весна будет управлять всем, getInstance() имеет только вернуть экземпляр singleton, созданный весной?

+3

Не записывайте код, который делает это. Используйте инъекцию зависимостей вместо этого уродливого приспособления. –

+5

По умолчанию весенние бобы являются одиночными. Попробуйте использовать инъекцию зависимостей, и весна будет делать это за вас. –

+0

Если я хорошо понимаю, больше не нужно использовать одноэлементный шаблон в приложении Spring? –

ответ

1

Я пришел к такому же выводу и аналогичной реализации, как и вы. Если кому-то нужен шаблон Singleton, то это способ сделать это с помощью Spring. Мне жаль, что я не видел этот пост раньше.

Некоторые люди не понимают, что Singleton Pattern отличается от Singleton, определенной весной, что объясняется здесь: Singleton design pattern vs Singleton beans in Spring container

Это сложно обойти отражения, который используется Spring, который эффективно игнорирует частный модификатор доступа.

Сказав это, некоторые люди ненавидят Singleton Pattern, как можно видеть на этой должности: http://puredanger.github.io/tech.puredanger.com/2007/07/03/pattern-hate-singleton/

Это вызывает меня пересмотреть, используя шаблон проектирования Singleton и вместо того, чтобы использовать Spring Singleton вместо.

Смежные вопросы