【问题标题】:Java, dependency injection singleton?Java,依赖注入单例?
【发布时间】:2016-03-29 02:53:53
【问题描述】:

我有以下代码:

public class DummyService {

  // Create new DummyModel with default value, 
  // Set value read from config file
  private static final DummyModel INSTANCE = new DummyModel(Play.application().configuration().getString('some-value'));

  public static DummyModel get() {
     return INSTANCE;
  }
}

我使用它:

 DummyService.get().someMethod();

现在我正在尝试编写使用此 DummyService 的单元测试,但这很难,因为 DummyModel 静态实例是从某个配置文件创建的。

我正在尝试使用依赖注入模式创建单例,但我真的不知道我是否做得对。 我创造了什么:

@Singleton
public class DummyService {
  private Configuration config;
  private DummyModel dummy;

  @Inject
  public DummyService(Configuration config) {
    this.configuration = config;
    this.dummy = new DummyModel(config.getString('some-value'));
  }
}

我每次都必须创建新的 DummyService 并提供配置吗?

DummyModel 还会是单例吗?

我应该使用 setter 还是 ctor 注入?

我可以将默认值设置为 config 并创建没有参数的新 CTOR,仅:

     private Configuration config = Play.application().configuration();

     @Inject
      public DummyService() {
        this.dummy = new DummyModel(config.getString('some-value'));
      }

【问题讨论】:

    标签: java playframework dependency-injection singleton


    【解决方案1】:

    有一个用于创建 DummyModel 的工厂类并将其作为构造函数参数注入。这样更容易测试,因为您可以轻松地模拟 DummyModel 进行单元测试。

    public DummyService (DummyModel dummyModel) {
        this.dummyModel = dummyModel;
    }
    

    在您的 DummyModelFactory 类中包含以下行,以便更清晰和目的。

    this.dummy = new DummyModel(config.getString('some-value'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2015-05-10
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多