gpt4 book ai didi

java - Spring BeanFactory 作为 Swing 应用程序中的单例

转载 作者:行者123 更新时间:2023-12-02 08:21:41 34 4
gpt4 key购买 nike

我目前正在重构一个大型 Swing 应用程序,以便从 XmlBeanFactory 获取一些对象。

许多不同的类可以使用它,我想知道共享这个 beanFactory 的最佳方式是什么。

  • 我应该创建一个 Singleton 来共享此 XmlBeanFactory 吗?

    单例类 { 公共(public)静态 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 后对其进行强制转换。

关于java - Spring BeanFactory 作为 Swing 应用程序中的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5355082/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com