简体   繁体   English

@PostConstruct和继承的顺序

[英]Order of @PostConstruct and inheritance

Let's suppose we have the following classes 我们假设我们有以下课程

public abstract class AbstractFoo {

    @PostConstruct
    private void doIt() {
       //
    }
}

public class Foo extends AbstractFoo {

    @PostConstruct
    private void doIt() {
       //
    }
}

When AbstractFoo.doIt() and Foo.doIt() will be called - what is the order? 当调用AbstractFoo.doIt()和Foo.doIt()时 - 命令是什么?

@PostConstruct is the last thing to get executed in the initialization of a given managed bean, relative to its position in the inheritance chain. @PostConstruct是在给定托管bean的初始化中执行的最后一件事,相对于它在继承链中的位置。 From the spec 从规格

The container must ensure that: 容器必须确保:

  • Initializer methods (ie @PostConstruct ) declared by a class X in the type hierarchy of the bean are called after all injected fields declared by X or by superclasses of X have been initialized. 在由X或X的超类声明的所有注入字段已初始化之后,将调用由bean的类型层次结构中的类X声明的初始化方法(即@PostConstruct )。

  • Any @PostConstruct callback declared by a class X in the type hierarchy of the bean is called after all initializer methods declared by X or by superclasses of X have been called , after all injected fields declared by X or by superclasses of X have been initialized. X声明的所有初始化方法或 X的超类已初始化之后,在调用X或超类X声明的所有初始化方法之后,调用 bean类型层次结构中由类X声明的任何@PostConstruct回调。

Pro Tip: With CDI 2.0, you can use @Inject to declare an initializer method as an alternative @PostConstruct and the restriction that you can have only one in a given class. 专业提示:使用CDI 2.0, 您可以使用@Inject声明初始化方法作为替代@PostConstruct以及您在给定类中只能拥有一个的限制。 The difference here is that @PostConstruct is still executed last and is the only place you can be guaranteed that all injected components will be available. 这里的区别在于@PostConstruct 仍然是最后执行的,并且是唯一可以保证所有注入的组件都可用的地方。

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

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