3 Replies Latest reply on Jul 18, 2010 2:53 AM by swd847

    Normal-scoped beans and constructors

    wujek
      Hi. I have the following application:


      public class Main {

          public static void main(String[] args) {
              new StartMain(null).go();
          }
      }


      class StartObserver {

          void printHello(@Observes ContainerInitialized event, SomeBean bean) {
              System.out.println("started!");
              bean.method();
          }
      }


      @ApplicationScoped
      class SomeBean {

          public SomeBean() {
              System.out.println(getClass().getName() + "() executing a very expensive operation");
          }

          public void method() {
              System.out.println(getClass().getName() + ".m()");
          }
      }


      When it executes (Weld-se) I get the following output:

      com.test.SomeBean_$$_javassist_2() executing a very expensive operation
      started!
      com.test.SomeBean() executing a very expensive operation
      com.test.SomeBean.m()

      As you can see, the proxy generated for the bean calls the superclass's constructor. It may happen that the constructor does something that has to be done only once, in which case the whole application fails (like some write to the database that fails with an exception when such entry already exists).
      Agreed, according to most (if not all) DI gurus no work should be done in the constructor, but what if? It is not a law, and this apparently would not work for Weld and its proxies. Is it the desired behavior? Or am I doing things wrong?

      Wuj
        • 1. Re: Normal-scoped beans and constructors
          wujek

          Does this mean nobody can answer this doubt?

          • 2. Re: Normal-scoped beans and constructors
            andygibson.contact.andygibson.net

            It seems strange that the constructor would be called twice (in anything). Try printing out the toString() in the constructor to see if the two instances are the same. These aren't singletons, so it is possible that there could be multiple instances.


            The problem is that with a managed bean environment, bean construction is as much out of your hands as memory allocation is in a memory managed environment like java.


            Cheers,


            Andy Gibson

            • 3. Re: Normal-scoped beans and constructors
              swd847

              This is a JVM level restriction, however JVM's usually have a platform specific way of creating a bean without using the constructor. To enable this in weld put an empty file in


              META-INF/org.jboss.weld.enableUnsafeProxies
              



              and the constructor will not get called. You may need a more up to date version of weld though, as I am not sure when this was added.