我正在尝试使用 Java EE 6 构建一个应用程序。开发是在 TomEE 1.7 上完成的。由于各种原因,我必须通过服务生产者创建大部分 CDI 托管对象。然而,当我这样做时,所创建的 bean 的 @PostConstruct 注释方法不会被调用。如果我将服务生产者排除在外并让 CDI 直接通过其构造函数创建对象,那么它确实会被调用。这是正常现象,还是 TomEE 自带的 CDI 提供程序(Open WebBeans)的 bug
谢谢
最佳答案
这是正常行为。当容器初始化 bean 时,将调用 @PostConstruct
方法。请参阅Weld Reference :
Simplifying just a little, things happen in this order:
First, the container calls the bean constructor (the default constructor or the one annotated
@Inject
), to obtain an instance of
the bean.Next, the container initializes the values of all injected fields of the bean.
- Next, the container calls all initializer methods of bean (the call order is not portable, don’t rely on it).
- Finally, the
@PostConstruct
method, if any, is called.
但是,在生产者方法的情况下,您可以完全控制对象的创建方式,因此您可以自己调用任何需要的方法。请注意,在生产者方法中,对象通常是使用 new 创建的,因此带注释的字段不会被初始化。再次检查producer method documentation可能的解决方案(注入(inject)生产者方法,@New
)
关于jakarta-ee - 使用服务生产者的 CDI PostConstruct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26424891/