2

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!

SorryForAsking
  • 323
  • 2
  • 18
  • It's all wrong. You're trying to use `@PostConstruct` to initialize `someService`, which should be injected. – Kayaman Oct 04 '19 at 10:29
  • Why are you initializing something (`SomeService` in this case) which is actually meant to be injected/autowired? Also, a method annotated with `@PostConstruct` is generally used to consume the injected bean or do whatever after this bean is ready. – isank-a Oct 04 '19 at 10:39
  • @Isank I have never used these annotations, so i've done this wrong. i just need to initialize "someService" right after creating an instance of ClassChild (without explicit call of init()). – SorryForAsking Oct 04 '19 at 10:48

2 Answers2

3

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

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

Abdullajon
  • 366
  • 3
  • 12