3 Replies Latest reply on Aug 28, 2010 5:03 AM by asiandub

    Constructor Injection vs Field Injection

    nimo22

      Am I right with this:


      Using Constructor Injection of Object A, all objects are instantly injected when instantiating A.


      Using Field Injection of Object A, field injected Objects are only injected when instantiating or invoking these field injected Objects, that means field injected Objects are not injected after creating the Instance of Object A.

        • 1. Re: Constructor Injection vs Field Injection
          nimo22

          Okay according to weld-spec (4.1):




          Dependency injection always occurs when the bean instance is first instantiated by the container. Simplifying just a little, things happen in this order:
          
          • First, the container calls the bean constructor (the default constructor or the one annotated @Inject), to obtain an instance of the bean.
          
          • Next, the container initializes the values of all injected fields of the bean.
          
          • Next, the container calls all initializer methods of bean (the call order is not portable, don't rely on it).
          
          • Finally, the @PostConstruct method, if any, is called.
          



          For Constructor Injection, it is obvious.


          Fild injection also happens eagerly. Is there any support for lazy injection?

          • 2. Re: Constructor Injection vs Field Injection
            swd847

            If the bean that is being injected is normal scoped then only the proxy is injected, the actual bean will not be created until you invoke a method on the proxy.

            • 3. Re: Constructor Injection vs Field Injection
              asiandub



              Field injection also happens eagerly. Is there any support for lazy injection?

              ... this is the main difference between Seam 2 and CDI. While Seam 2 physically injected Seam components into each other, CDI has the proxy concept for all normal scoped beans. Maximum laziness, if you want to put it like this ;-)