Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PostConstruct annotation and spring lifecycle

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

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");     } } 
like image 559
Daniele Avatar asked Jun 21 '17 16:06

Daniele


People also ask

What is @PostConstruct annotation in Spring?

When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.

What is the use of @PostConstruct annotation?

Annotation Type PostConstruct The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

Is @PostConstruct deprecated?

In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.

What is Spring life cycle?

The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.


1 Answers

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"

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

like image 150
Antoniossss Avatar answered Sep 20 '22 11:09

Antoniossss