SorryForAsking
SorryForAsking

Reputation: 373

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

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!

Upvotes: 2

Views: 3466

Answers (2)

Abdullajon
Abdullajon

Reputation: 366

Note that both @PostConstruct and @PreDestroy annotations are part of Java EE. And since Java EE has been deprecated in Java 9 and removed in Java 11 we have to add an additional dependency to use these annotations:

<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>

enter link description here

Upvotes: 2

Kayaman
Kayaman

Reputation: 73558

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.

Upvotes: 3

Related Questions