1 Reply Latest reply on Jan 4, 2016 7:20 AM by mkouba

    Newbie question on Weld SE

    tdudgeon

      I've got a stupid newbie problem with Weld SE. I know the general ideas pretty well and use CDI in a servlet environment but am struggling with the simple stuff!

      I have a bean that uses @Inject (Worker is just a standard class):

       

      public class Bean {

         @Inject
         private Worker worker;

       

         public Worker getWorker() {

         return worker;

        }

       

      And I want to us this in an SE app, so I have a Main class:

       

      public class Main {

       

         public static void main(String[] args) {

        Main main = new Main();

        main.works();

        System.out.println("--------------------------------------------");

        main.doesNotWork();

        }

       

         void works() {

        Weld weld = new Weld();

        WeldContainer container = weld.initialize();

        Bean mybean = container.select(Bean.class).get();

        System.out.println("Bean Worker: " + mybean.getWorker());

        }

       

         void doesNotWork() {

        Bean mybean = new Bean();

        System.out.println("Bean Worker: " + mybean.getWorker());

        }

      }

       

       

      Why does doesNotWork() work (doesn't not have the worker injected)?

      Surely the whole point of this is that all classes get scanned and can be treated as normal (but CDI injected) classes.

      And yes, I do have an empty META-INF/beans.xml

       

      Tim

        • 1. Re: Newbie question on Weld SE
          mkouba

          Hi Tim,

          doesNotWork() does not work because you instantiate the class manually. But the whole point is to let the CDI container manage the lifecycle (and perform the injection) of contextual instances. Still it is possible to work with unmanaged instances (see for example javax.enterprise.inject.spi.Unmanaged intended for use by integrators) .