1

I have classes as below. I want statements in constructor of DataService to be called itself after the application or DataService class has has been initialized and before DataHandler is intitalized. But dataLoader object is null in the constructor. I am new to guice and want to know how can i achieve this using GUICE

@Singleton
@Managed
class DataService{

    @Inject private DataLoader dataLoader;

   DataService(){
      dataLoader.load(); // I am trying to udnerstand why dataLoader is null?
   }
}

@Singleton
@Managed
class DataHandler{

    @EventHandler
    public void handle(StaticData data){
       //some logic om data
    }
}

Class StaticDataModule extends AbstractModule{

    @Override
    protected void configure(){
        bind(DataService.class).asEagerSingletin();
        bind(DataHandler.class).asEarSingleton();
    }
}

1 Answers1

1

dataLoader is null because it is not yet initialized

You request an injection of a field, yet you try to call it before it is even initialized.

In order, what is executed?

  1. The direct assignment of fields. This means private double pi = 3.14;
  2. The constructor.
  3. Everything outside the constructor

You have to understand that Guide is outside the constructor, even @Inject. When you instantiate an object, its constructor is first called, then the fields are injected. It's like in Spring or in Java EE: the initialization is done using another method, annotated in @PostConstruct. However Guide doesn't have such annotation.

So the solutions to solve your problem are

  1. either you inject your field as a constructor parameter, so that you can initialize during the constructor, or
  2. After your Injector is created, you get your instance and call its @PostConstruct-like method that you created.

Example:

Injector injector = Guice.createInjector(...);
DataService dataService = injector.getInstance(DataService.class);
dataService.init();

And your DataService is as follows:

class DataService {
  @Inject DataLoader loader;
  void init() {
    loader.load();
  }
}
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137