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
@PostConstruct annotation and spring lifecycle
提问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 @Autowired
annotated field in another class. Can I assume that the class is only injected after @PostConstruct
is 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 @PostConstruct
in that bean is called, then the answer is yes - @PostConstruct
is executed before bean is considered as "injectable"
如果您问的是@PostConstruct
在调用该 bean之后发生给定类的注入,那么答案是肯定的 -@PostConstruct
在 bean 被视为“可注入”之前执行
If you are asking if @PostConstruct
on given bean is executed after all injections has been done (on the same bean) - then yes - @PostConstruct
is executed after injections are commited to given bean. This is the reason it exists. Normally you could put @PostConstruct
actions 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
, @PreDestroy
is 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
(这意味着与可注入一样多)。