多种结构后方法?

2022-09-01 15:54:04

它在Java的PostConstruct文档页面中说:

只能使用此批注对一种方法进行批注

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

那么我错过了什么呢?在什么样的类中可以和不能存在多个构造后注释?


答案 1

是的,春天似乎没有遵循这个限制。我找到了处理这个注释的代码,它是,以及具体的方法: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);
            }
        }
    }

所以,弹簧支持多后结构


答案 2

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

我刚刚用WELD尝试了它,它像预期的那样抛出了一个异常:

WELD-000805: Cannot have more than one post construct method annotated with @PostConstruct for [EnhancedAnnotatedTypeImpl] public  class Test

推荐