Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple PostConstruct methods?

It says in Java's documentation page for PostConstruct that

Only one method can be annotated with this annotation

But I just tried annotating three methods of a standalone application with PostConstruct. No compile errors, and all three of them are invoked and executed smoothly.

So what am I missing? In what kind of class can and cannot exist multiple PostConstruct annotations?

like image 385
Luis Sep Avatar asked Mar 14 '14 09:03

Luis Sep


People also ask

Can we have multiple PostConstruct?

In a single class, it allows to have more than one @PostConstruct annotated method, and also the order of execution is random.

Is PostConstruct called only once?

Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.

What can I use instead of PostConstruct?

We can replace @PostConstruct with BeanFactoryPostProcessor and PriorityOrdered interface. The first one defines an action that ought to be executed after the object's instantiation. The second interface tells the Spring the order of the component's initialization.

Can PostConstruct be private?

The method on which PostConstruct is applied MAY be public, protected, package private or private. The method MUST NOT be static except for the application client.


1 Answers

Yes, it's seem Spring doesn't follow this restriction. I have found code to process this annotation which is InitDestroyAnnotationBeanPostProcessor, and the specific method:

public void invokeInitMethods(Object target, String beanName) throws Throwable {         Collection<LifecycleElement> initMethodsToIterate =                 (this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);         if (!initMethodsToIterate.isEmpty()) {             boolean debug = logger.isDebugEnabled();             for (LifecycleElement element : initMethodsToIterate) {                 if (debug) {                     logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());                 }                 element.invoke(target);             }         }     } 

So, spring support multi PostConstruct

like image 58
Wang Jun Avatar answered Sep 29 '22 08:09

Wang Jun