简体   繁体   中英

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.

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?

Will DummyModel still be singleton?

Should I use setter or ctor inject?

Can I set default value to config and create new CTOR that doesn't have arguments, only:

     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. this way this is easier to test as you can easily mock the DummyModel for your unit testing.

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

Have the below line inside your DummyModelFactory class for better clarity and purpose.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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