多个PostConstruct方法?

Lui*_*Sep 16 java javadoc postconstruct

它在Java的 PostConstruct 文档页面中说明了这一点

只有一个方法可以使用此注释进行注释

但我只是尝试用PostConstruct注释一个独立应用程序的三种方法.没有编译错误,并且所有三个都被调用并顺利执行.

那我错过了什么?什么样的类可以存在多个PostConstruct注释?

Wan*_*Jun 14

是的,看起来Spring并没有遵循这个限制.我找到了处理这个注释的代码InitDestroyAnnotationBeanPostProcessor,具体方法是:

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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以,spring支持多PostConstruct


Ste*_*all 5

这可能取决于您使用的CDI实现.你确实注入了对象,你有注释,不是吗?

我只是尝试使用WELD,它会按预期抛出异常:

WELD-000805: Cannot have more than one post construct method annotated with @PostConstruct for [EnhancedAnnotatedTypeImpl] public  class Test
Run Code Online (Sandbox Code Playgroud)