2 Replies Latest reply on Nov 10, 2008 9:47 AM by Alexey Aliferov

    The simplest POJO bean is created twice

    Alexey Aliferov Newbie
      I have some strange thing - in the simplest possible example the bean is created twice by Seam.
      I have one JSP page and one simplest bean:

      Bean:
      @Name("xbean") 
      @Scope(ScopeType.SESSION) 
      public class XBean { 
              private static int cre||ated = 0 ;
              private String text = "whatever";
              public XBean() {
                      ++created ;
                      text += created ;
                      System.out.println(created) }
              public String getText() {
                      System.out.println("get from " + created) ;
                      return text;
              }
      }

      JSP:
      <h:outputText value="#{xbean.text}" id="rep"/>

      I tried Seam 2.0.2SP1 and 2.1.0SP1. I use only jboss-seam.jar and jboss-el.jar. Transactions are not use.

      everything seems to work correctly, but the console output looks like that:
      1
      2
      get from 2

      So the bean is constructed twice and the second instance is used, BUT
      the outputText text value on the page is whatever1!!!!

      What could it be???





        • 1. Re: The simplest POJO bean is created twice
          Dan Allen Master

          You are confusing yourself a bit with your use of a static field. The getText() method is only called on the first instance. It just so happens that the static field has a value of 2 during the time of that call. You should return the hash code of the instance to verify this fact.


          You are correct that the constructor is called twice. This is one of those side effects of using Javassist, which is the object proxy library that Seam uses. What's happening is that Javassist is calling the default constructor to restore the object instance (somewhere low-level). However, the instance that results from the second invocation of that constructure is not used anywhere by the application.


          The lesson to be learned here is that you should not put resource intensive code in a constructor because proxying libraries such as Javassist may need to invoke the constructor from time-to-time. Instead, you should put setup code in a @PostConstruct or @Create method.

          • 2. Re: The simplest POJO bean is created twice
            Alexey Aliferov Newbie

            Thank you for your help.
            The first confusion about static field I figured out, it was a minor issue. The construction of the object twice is more interesting.
            What I found out that if I set @Entity annotation on the object then it is not created twice. But it gets no injections. According to what you say I would suppose that Javassist is not used with Entity classes.
            Do you know if this issue will be fix, it's kind of not nice, especially for beginners.