Multiple PostConstruct methods?
Asked Answered
P

6

28

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?

Polygamous answered 14/3, 2014 at 9:20 Comment(1)
What container are you using ?Cacus
C
25

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

Casablanca answered 6/7, 2016 at 1:42 Comment(0)
S
9

This probably depends on the CDI implementation you are using. You did inject the object, where you have the annotations, didn't you?

I just tried it with WELD, which throws an exception as expected:

WELD-000805: Cannot have more than one post construct method annotated with @PostConstruct for [EnhancedAnnotatedTypeImpl] public  class Test
Skye answered 14/3, 2014 at 9:27 Comment(0)
S
3

Spring support multi PostConstruct, in runtime the application will choose to run first, the one ordered in the top in the class. see example below:

@PostConstruct
private void firstPostConstructor() {
 LOGGER.info("First Post Constructor");
}

@PostConstruct
private void secondPostConstructor() {
 LOGGER.info("Second Post Constructor");
}

@PostConstruct
public void thirdPostConstructor() {
 LOGGER.info("Third Post Constructor");
}

Then the execution will be ordered accordingly as the picture below:

enter image description here

Stunt answered 18/8, 2020 at 11:25 Comment(2)
This means they are not following the interface. I would avoid using it more than once, imagine it you plan to migrate this you will hit the issue and lose time there. It is always recommend to follow the spec :)Cacus
This is not reproduced for me. The order is as follows: Second Post Constructor, Third Post Constructor, First Post ConstructorNicotinism
S
2

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

@PostConstruct
    public void myInit() {
        System.out.println("inside the post construct method1. ");
    }
    
    @PostConstruct
    public void myInit2() {
        System.out.println("inside the post construct method2. ");
    }
    
    @PostConstruct
    public void myInit3() {
        System.out.println("inside the post construct method3. ");
    }

    @PostConstruct
    public void myInit4() {
        System.out.println("inside the post construct method4. ");
    }

Output

FINE: Creating shared instance of singleton bean 'employee'
inside the default constructor....
inside the post construct method4. 
inside the post construct method. 
inside the post construct method2. 
inside the post construct method3. 
Spacing answered 24/4, 2021 at 10:4 Comment(0)
S
0

I tested with one class with 2 @PostConstruct, then I get the error WELD-000805: Cannot have more than one post construct method But it's ok if I have multiple @PostConstruct, each in one class. So I guess this sentence means: Only one method per class can be annotated with this annotation.

Siusiubhan answered 28/2, 2020 at 1:20 Comment(0)
B
0

As of 2023 Jakarta EE docs still say:

Only one method in a given class can be annotated with this annotation.

8 - https://jakarta.ee/specifications/platform/8/apidocs/javax/annotation/postconstruct

10 - https://jakarta.ee/specifications/platform/10/apidocs/jakarta/annotation/postconstruct

And it still works in Spring, though I cannot find Spring docs for @PostConstruct other than https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/postconstruct-and-predestroy-annotations.html that don't specify 1 or N annotating is allowed.

I guess it is one of those examples, when alternative CDI implementations say, fully compatible with Spring and standards, but you may expect errors along the way, if you try to step away from Spring.

Breastpin answered 19/5, 2023 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.