【问题标题】:Create Singleton with function/constructor arguments (usefull for e.g. injection)使用函数/构造函数参数创建单例(对例如注入有用)
【发布时间】:2011-07-19 11:43:06
【问题描述】:

我们使用 spring 来构造/注入我们的 java bean。这是一个sn-p:

<bean id="myAppConfigs" class="my.cool.webapp.ApplicationConfig" scope="singleton">
    <constructor-arg value="8080" />
    <constructor-arg value="MyAppName1" /> 
</bean>

我们在

中使用单例模式
public static ApplicationConfig getCurrentInstance(ServletContext sctx) {
    if (instance == null) {
                WebApplicationContext wac = null;
                if (sctx != null) {
                    wac = WebApplicationContextUtils.getWebApplicationContext(sctx);
                }
return (ApplicationConfig) wac.getBean("myAppConfigs");

由于 bean 只读取一些始终相同的属性,我怀疑可能存在问题。但我仍然很好奇一个很好的线程安全的方法来实现它 当然有Double Checked Locking with usage of volatile 是线程安全的。 但是是否有另一种方法可以将Initialization on demand holder idiom 与函数/构造函数参数一起使用?

【问题讨论】:

  • 这与 JSF 有什么关系?

标签: java spring design-patterns singleton


【解决方案1】:
public static ApplicationConfig getCurrentInstance(ServletContext sctx) {
  if (sctx == null) {
    throw new AssertionError("ServletContext is null");
  }
  WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sctx);
  if (wac == null) {
    throw new AssertionError("No ApplicationContext associated with ServletContext");
  }
  return (ApplicationConfig) wac.getBean("myAppConfigs");
}

这是很多线程安全的。更好的是一直努力使用注入(通过注解或 XML bean 定义),但这并不总是可能的。

将 Spring (DI) 与单例模式和显式线程同步混合使用是一种反模式,并不是真正需要的。 Spring bean 工厂本身是线程安全的,因此您不需要在其之上添加任何额外的锁定/同步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多