0

Consider this example:

public class GuiceExample {
    @Inject
    private IDataManager dataManager;

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {
                bind(IDataManager.class).to(DataManager.class);
            }
        });

        GuiceExample example = injector.getInstance(GuiceExample.class);
        example.dataManager.printData();
    }

    public static interface IDataManager {
        void printData();
    }

    public static class DataManager implements IDataManager {

        @Override
        public void printData() {
            System.out.println("I print data.");
        }

    }
}

Is it possible to do something right after GuiceExample class has been initialized (the fields are injected)?

I have tried adding a @PostConstruct method just in case...but it is not being called.

@PostConstruct
private void fieldsAreInjected() {
    System.out.println("Checking if datamanager is null:");
    System.out.println(dataManager == null);
}

I tried to find anything on the web, but got nothing. Is it possible or the @Inject on the constructor is the only way?

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • 1
    Check this answer https://stackoverflow.com/a/2093874/3287786 and thread. – I.G. Mar 07 '20 at 12:15
  • @I.G. I found this answer 2 mins before you comment me. Give me sometime, I will probably delete my question or mark it as duplicate. – George Z. Mar 07 '20 at 12:23

0 Answers0