2014-03-14 55 views
11

它说,在Java's documentation页面PostConstruct该多PostConstruct方法?

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

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

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

回答

4

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

我只是WELD,会抛出一个异常尝试了预期:

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

是的,这似乎春天不遵循此限制。我发现代码来处理这个注释是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); 
      } 
     } 
    } 

所以,弹簧支撑多PostConstruct

相关问题