簡體   English   中英

Spring BeanFactory作為Swing應用程序中的單例

[英]Spring BeanFactory as a singleton in a Swing application

我正在重構一個大的Swing應用程序,以便從XmlBeanFactory中獲取一些對象。

許多不同的類都可以使用它,我想知道分享這個beanFactory的最佳方式是什么。

  • 我應該創建一個Singleton來共享這個XmlBeanFactory嗎?

    class Singleton {public static XmlBeanFactory getBeanFactory(){(...)}}

  • 或者我應該為我的對象添加一些setter(丑陋:它增加了一些依賴...)

  • 另一種方案?

謝謝

使用靜態單例是一種可行的方法。 我還沒有找到更好的解決方案。 它有點令人不滿意,因為單例必須在使用之前用布線文件初始化,如果不這樣做會導致bean創建異常,還有一件事需要記住。

public final class SpringUtil {

private static ApplicationContext context = null;
private static Set<String> alreadyLoaded = new HashSet<String>();

/**
 * Sets the spring context based off multiple wiring files. The files must exist on the classpath to be found.
 * Consider using "import resource="wiring.xml" in a single wiring file to reference other wiring files instead.
 * Note that this will destroy all previous existing wiring contexts.
 * 
 * @param wiringFiles an array of spring wiring files
 */
public static void setContext(String... wiringFiles) {
    alreadyLoaded.clear();
    alreadyLoaded.addAll(Arrays.asList(wiringFiles));
    context = new ClassPathXmlApplicationContext(wiringFiles);
}

/**
 * Adds more beans to the spring context givin an array of wiring files. The files must exist on the classpath to be
 * found.
 * 
 * @param addFiles an array of spring wiring files
 */
public static void addContext(String... addFiles) {
    if (context == null) {
        setContext(addFiles);
        return;
    }

    Set<String> notAlreadyLoaded = new HashSet<String>();
    for (String target : addFiles) {
        if (!alreadyLoaded.contains(target)) {
            notAlreadyLoaded.add(target);
        }
    }

    if (notAlreadyLoaded.size() > 0) {
        alreadyLoaded.addAll(notAlreadyLoaded);
        context = new ClassPathXmlApplicationContext(notAlreadyLoaded.toArray(new String[] {}), context);
    }
}

/**
 * Gets the current spring context for direct access.
 * 
 * @return the current spring context
 */
public static ApplicationContext getContext() {
    return context;
}

/**
 * Gets a bean from the current spring context.
 * 
 * @param beanName the name of the bean to be returned
 * @return the bean, or throws a RuntimeException if not found.
 */
public static Object getBean(final String beanName) {
    if (context == null) {
        throw new RuntimeException("Context has not been loaded.");
    }
    return getContext().getBean(beanName);
}

/**
 * Sets this singleton back to an uninitialized state, meaning it does not have any spring context and
 * {@link #getContext()} will return null. Note: this is for unit testing only and may be removed at any time.
 */
public static void reset() {
    alreadyLoaded.clear();
    context = null;
}

}

使用更新版本的springframework,您可以使用泛型使getBean()返回比Object更具體的類,這樣您就不必在獲取它之后強制轉換bean。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM