简体   繁体   English

带有注释@PostConstruct(javax)的方法不会调用

[英]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?是否可以在使用 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.在调用构造函数后,我将@Inject注释(javax.inject.Inject)放在要在方法中使用@PostConstruct注释(javax.annotation.PostConstruct)初始化的字段上,但未调用此 init 方法和 NPE 崩溃。

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?如何在调用 ClassChild 构造函数后立即调用 init() 方法? I would be very grateful for any help!如果有任何帮助,我将不胜感激!

Your ClassChild is not a managed object (eg a @Component in Spring), so neither @Inject nor @PostConstruct will work.您的ClassChild不是托管的 object(例如 Spring 中的@Component ),因此@Inject@PostConstruct都不起作用。 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.您不应该调用构造函数,您需要让框架初始化ClassChild ,之后框架还将调用@PostConstruct方法。

Note that both @PostConstruct and @PreDestroy annotations are part of Java EE.请注意,@PostConstruct 和 @PreDestroy 注释都是 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:并且由于 Java EE 已在 Java 9 中被弃用并在 Java 11 中被删除,我们必须添加额外的依赖项来使用这些注释:

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

enter link description here在此处输入链接描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM