简体   繁体   English

Java,依赖注入单例?

[英]Java, dependency injection singleton?

I have following code: 我有以下代码:

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;
  }
}

And I use it: 我用它:

 DummyService.get().someMethod();

Now I'm trying to write unit test that use this DummyService, but this is hard since DummyModel static instance is create from some config file. 现在,我正在尝试编写使用此DummyService的单元测试,但这很难,因为DummyModel静态实例是通过某些配置文件创建的。

I'm trying to create singleton with dependency injection pattern, but I don't really know if I'm doing it right. 我正在尝试使用依赖项注入模式创建单例,但是我真的不知道我是否做对了。 What I created: 我创造了什么:

@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'));
  }
}

Will I have to create new DummyService and provide config each time? 我是否必须每次都创建新的DummyService并提供配置?

Will DummyModel still be singleton? DummyModel仍然是单例吗?

Should I use setter or ctor inject? 我应该使用setter还是ctor注入?

Can I set default value to config and create new CTOR that doesn't have arguments, only: 我可以将默认值设置为config并创建仅不带参数的新CTOR:

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

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

Have a factory class for creating DummyModel and inject it as constructor argument. 有一个用于创建DummyModel的工厂类,并将其作为构造函数参数注入。 this way this is easier to test as you can easily mock the DummyModel for your unit testing. 这样,这很容易测试,因为您可以轻松模拟DummyModel进行单元测试。

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

Have the below line inside your DummyModelFactory class for better clarity and purpose. 在您的DummyModelFactory类中包含以下行,以提高清晰度和用途。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM