Multiple PostConstruct methods?

﹥>﹥吖頭↗ 提交于 2020-05-25 10:24:54

问题


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?


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/22400705/multiple-postconstruct-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!