0

I have a class as follows:

class FooBar {
    @Autowired
    SomeObj someObj;

    FooBar() {
        // Cant call this here as someObj is not yet initialized
        // someObj.someMethod();
    }

    private void init() {
        someObj.someMethod();
    }
}

I'm creating the object of fooBar as follows:

FooBar fooBar = new FooBar();

How can I automatically call init after creation and autowiring are complete?

Doctor
  • 59
  • 12
ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • use `@PostConstruct` https://stackoverflow.com/questions/3406555/why-use-postconstruct – diginoise Sep 06 '18 at 09:17
  • Autowiring does not even work this way. If you let _Spring_ handle the instantiation you can use `@PostConstruct` to perform your intialization. – trylimits Sep 06 '18 at 09:18
  • @diginoise @ trylimits that doesn't work when instantiating objects using new. – ayushgp Sep 06 '18 at 09:19
  • 1
    @ayushgp that's why I stated, that also `@Autowiring` doesn't work if you instantiate using `new`. Therefore there's no way to get `init` called _after_ autowiring is complete, because that just never happens. You have to use the _Spring_ way to create your object or process your created instance via a `AutowireCapableBeanFactory`. – trylimits Sep 06 '18 at 10:43
  • There is a way to inject dependencies into object created via constructor. Check answers to this question https://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring. However this is a bad hack and if you have to do so you really need to rethink your architecture – Ivan Sep 06 '18 at 11:00

0 Answers0