2011-03-18 54 views
0

單身我目前正在重構,以大搖擺應用從XmlBeanFactory的得到一些對象。春Bean工廠在Swing應用程序

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

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

    類辛格爾頓 { 公共靜態XmlBeanFactory的方法getBeanFactory(){ (...) }}

  • ,或者我應該有的setter方法添加到我的對象(醜:它增加了一些depedencies ... )

  • 另一種解決方案?

感謝

回答

2

使用靜態單是OK的路要走。我還沒有找到更好的解決方案。它有點令人不滿意,因爲單例在使用之前必須使用佈線文件進行初始化,否則會導致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; 
} 

}

有了你可以使用泛型,使的getBean的springframework的較新版本()返回一個更具體的類比對象,所以你沒有得到它後,投下您的bean。