Method with annotation @PostConstruct (javax) doesn't call

Artem :

Is it possible to call a specific initialization method right after calling the constructor using annotations from javax?

I put the @Inject annotation (javax.inject.Inject) over the field that I want to initialize in the method with the @PostConstruct annotation (javax.annotation.PostConstruct) right after the constructor is called, but this init method is not called and NPE crashes.

public class ClassChild extends ClassParent{

   @Inject
   private SomeService someService;


   @PostConstruct
   public void init(){

      someService = new SomeService(getSomeValues())  // getSomeValues() a method from parent
   }

Am I using these annotations correctly? What is the problem? How to call the init() method right after calling the ClassChild constructor? I would be very grateful for any help!

Kayaman :

Your ClassChild is not a managed object (e.g. a @Component in Spring), so neither @Inject nor @PostConstruct will work. You're not supposed to call the constructor, you need to have the framework initialize ClassChild, after which the framework will also call the @PostConstruct method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309977&siteId=1