Java @PostConstruct 注释和 spring 生命周期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44681142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:40:56  来源:igfitidea点击:

@PostConstruct annotation and spring lifecycle

javaspringioc-container

提问by Daniele

I'm new to Spring, I would like to know:

我是Spring的新手,我想知道:

I have a java class annotated with @Component(spring) and inside I have a method annotated with @PostConstruct. The class is then referenced by @Autowiredannotated field in another class. Can I assume that the class is only injected after @PostConstructis called?

我有一个用@Component(spring)注释的 java 类,在里面我有一个用@PostConstruct. 然后该类被@Autowired另一个类中的带注释的字段引用。我可以假设该类仅在@PostConstruct被调用后注入吗?

@Component
class AuthenticationMetrics {

    private static final MetricRegistry metrics = new MetricRegistry();

    final Counter requestsTotal;

    final Meter guestLogins;

    final Meter kfUserLogins;

    final Timer guestLoginResponseTime;

    final Timer kfLoginResponseTime;

    @PostConstruct
    public void populateMetricsRegistry() {
        metrics.counter("authentication.requests.totals");
    }
}

采纳答案by Antoniossss

If you are asking is injection of given class happening after @PostConstructin that bean is called, then the answer is yes - @PostConstructis executed before bean is considered as "injectable"

如果您问的是@PostConstruct在调用该 bean之后发生给定类的注入,那么答案是肯定的 -@PostConstruct在 bean 被视为“可注入”之前执行

If you are asking if @PostConstructon given bean is executed after all injections has been done (on the same bean) - then yes - @PostConstructis executed after injections are commited to given bean. This is the reason it exists. Normally you could put @PostConstructactions into the constructor. However, when new object is created (constructor is called) injections are not performed yet - so any initialization that depends on injected objects would fail due to NPE. That is why you need @PostConstruct

如果您询问是否@PostConstruct在所有注入完成后执行给定的 bean(在同一个 bean 上) - 那么是 -@PostConstruct在注入被提交给给定的 bean 之后执行。这就是它存在的原因。通常,您可以将@PostConstruct操作放入构造函数中。但是,当创建新对象(调用构造函数)时,还没有执行注入——因此任何依赖于注入对象的初始化都将因 NPE 而失败。这就是为什么你需要@PostConstruct

回答by Nico Van Belle

The handling of annotations such as @PostConstruct, @Resource, @PreDestroyis done via a BeanPostProcessor, in this case the CommonAnnotationBeanPostProcessor. You can see in the following diagram from Spring that these BPP's are handled afterDependency Injection but beforeBean Ready For Use(Which means as much as injectable).

注释如的处理@PostConstruct@Resource@PreDestroy通过完成BeanPostProcessor的,在这种情况下,CommonAnnotationBeanPostProcessor会。您可以在 Spring 的下图中看到,这些 BPP 是依赖注入之后但之前处理的Bean Ready For Use(这意味着与可注入一样多)。

enter image description here

在此处输入图片说明