[英]@PostConstruct annotation and spring lifecycle
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
.我有一个用
@Component
(spring) 注释的 java 类,在里面我有一个用@PostConstruct
注释的方法。 The class is then referenced by @Autowired
annotated field in another class.然后该类被另一个类中的
@Autowired
注释字段引用。 Can I assume that the class is only injected after @PostConstruct
is called?我可以假设只有在调用
@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");
}
}
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"如果您问的是在调用该 bean 中的
@PostConstruct
之后是否发生给定类的注入,那么答案是肯定的 - 在 bean 被视为“可注入”之前执行@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.如果你问是否
@PostConstruct
上给出bean是所有注射已经完成(在同一个bean)后执行-然后是- @PostConstruct
被注射致力于为定bean后执行。 This is the reason it exists.这就是它存在的原因。 Normally you could put
@PostConstruct
actions into the constructor.通常,您可以将
@PostConstruct
操作放入构造函数中。 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.但是,当创建新对象(调用构造函数)时,还没有执行注入——因此任何依赖于注入对象的初始化都将因 NPE 而失败。 That is why you need
@PostConstruct
这就是为什么你需要
@PostConstruct
The handling of annotations such as @PostConstruct
, @Resource
, @PreDestroy
is done via a BeanPostProcessor , in this case the CommonAnnotationBeanPostProcessor . @PostConstruct
、 @Resource
、 @PreDestroy
等注解的处理是通过BeanPostProcessor完成的,在本例中是CommonAnnotationBeanPostProcessor 。 You can see in the following diagram from Spring that these BPP's are handled after Dependency Injection but before Bean Ready For Use
(Which means as much as injectable).您可以在 Spring 的下图中看到,这些 BPP在依赖注入之后但在
Bean Ready For Use
之前处理(这意味着与可注入一样多)。
Yes.是的。 Bean creation workflow is:
Bean创建工作流程是:
@Autowired
fields @Autowired
字段@Autowired
setters @Autowired
二传手postProcessBeforeInitialization()
, ie @PostConstruct
called by CommonAnnotationBeanPostProcessor
postProcessBeforeInitialization()
,即CommonAnnotationBeanPostProcessor
调用的@PostConstruct
InitializingBean.afterPropertiesSet()
postProcessAfterInitialization()
postProcessAfterInitialization()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.