@PostConstruct注释和spring生命周期 [英] @PostConstruct annotation and spring lifecycle

查看:177
本文介绍了@PostConstruct注释和spring生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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
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")

  }

}


推荐答案

如果你问的是在调用该bean的 @PostConstruct 之后注入给定的类,那么答案是肯定的 - @PostConstruct

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上)执行给定的bean - 然后是 - @PostConstruct 在注入被提交给给定bean之后执行。这就是它存在的原因。通常,您可以将 @PostConstruct 操作放入构造函数中。但是,当创建新对象(调用构造函数)时,还没有执行注入 - 因此任何依赖于注入对象的初始化都会因NPE而失败。这就是为什么你需要 @PostConstruct

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注释和spring生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆