2 Replies Latest reply on Apr 20, 2016 6:18 AM by ctwx

    Why injection through new does not work?

    ctwx

      Hello,

       

      I am trying to inject a List in an object that's called through a number of elements. Using the @Singleton annotation and injecting Lister in my UI class, it works.

       

      I have:

      • App that creates a WeldContainer
      • It creates an object of UI and runs it's start() method
      • in the start() method it creates a new object of Lister with "new Lister()"
      • in Lister there's an attribute that is injected with @Inject and the @FooFinder qualifier
      • in Lister is a getFoos() method that returns finder.getFoos()
      • Finder has an attribute List<Foo> which is injected by a @Produces in FooCreator and has a getFoos() method which returns this list
      • FooCreator simply returns a list:
        @Produces public List<Foo> createFoos() {
            List<Foo> fooList = new ArrayList<>();
            fooList.add(new Foo());
            fooList.add(new Foo());
            fooList.add(new Foo()));
            return fooList;
        }
        

      When I run lister.getFoos().stream().forEach(System.out::println); in my UI class with the new Lister() generated Lister, the fooList is null.

      I added @Singleton to Lister and tried @Inject Lister lister, then it works.

       

      Why is that? I thought it gets injected because the injection annotations will make sure that fooList will be injected.

       

      I uploaded the complete code to Github: WeldProducesTest/src/main/java/com/mycompany/weldproducestest at master · cwansart/WeldProducesTest · GitHub

        • 1. Re: Why injection through new does not work?
          manovotn

          Hi Christian

           

          First of all, thanks for the code, it makes things much easier to grasp

           

          Why is that? I thought it gets injected because the injection annotations will make sure that fooList will be injected.

          Weld cannot help you here, because you manually created the object. If you let Weld take care of the creation process (e.g. use the objects via @Inject) it will also resolve the injection point for you. That is why your latter case works fine.

          The magic behind the creation involves much more than just calling new Object(), along with injection point resolution there is proxy creation etc.

          • 2. Re: Why injection through new does not work?
            ctwx

            Thank you for your Answer. I guess I just misunderstood the concept. I thought, when I start the injection in the main method then it would does it magic on "new" calls as well. But after rethinking it makes sense!