14 Replies Latest reply on Dec 7, 2016 3:03 AM by Martin Kouba

    Programmatically added observer methods and lifecycles

    Laird Nelson Apprentice

      I had a question about what happens when you programmatically add an observer method to a bean.

       

      In my case, I am programmatically adding an observer method that @Observes @Initialized(ApplicationScoped.class) final Object payload.

       

      If I explicitly code up this observer method and actually add it to the source code of my bean, I notice that (as I would of course expect) the bean is instantiated by the container when the observer method is notified (section 5.5.6 of the specification requires this).  That is, upon startup a contextual instance of the bean is created so that this observer method may be called.  This has the nice side effect of allowing me to perform certain actions at startup.

       

      Now, if I do not have this method in my source code, but instead, using a portable extension, programmatically add an observer method that does the same thing, I observe that the bean is not instantiated by the container when the observer method is notified.

       

      At some level, this makes sense: in order to invoke the source-code-defined observer method, obviously there needs to be an object to invoke it on!  And in the programmatically-added case, the observer method kind of stands on its own, so can conceivably be invoked without requiring that the bean be instantiated.

       

      But on the other hand, this seems like a strange disparity caused only by where the observer method happens to be.

       

      I also recognize that I could build my programmatically-added observer method with a Function that uses the BeanManager's getReference() method to obtain a contextual reference to my bean.

       

      My real question, then, is: is this an oversight?  Should the container instantiate the bean when a programmatically added observer method is notified?