• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object is not injected (it's null) when calling through another object (weld-se)

 
Christian Wansart
Ranch Hand
Posts: 32
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am trying to inject a list of objects via @Produces. I have an App.java, which uses the WeldContainer to create an instance of UI. Then I run UI.start(), which creates an object of Lister by calling "new Lister()". Lister has a private Finder which is injected via @FooFinder qualifier. It has a getFoos() method which calls finder.getFoos(). Finder.getFoos() just returns it's private attribute fooList, which is injected by using an @Produces annotation. The @Produces public List<Foo> createFoos() is defined in FooCreator.java.

Underneath you'll find my code. You can see the whole project on my git repo: https://github.com/cwansart/WeldProducesTest/tree/master/src/main/java/com/mycompany/weldproducestest

App.java


UI.java


Lister.java


Finder.java


FooFinder.java


FooCreator.java


Foo itself is just a small class where nothing happens.


When I call lister.getFoos() in the UI class it's null. Why is that so? When I just inject the fooList in my UI class, it works.
 
Christian Wansart
Ranch Hand
Posts: 32
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I might have found an answer! I added @Singleton to my Lister. Then I added

to my UI class as attribute. Now this works:


However, I'm still not sure why it's not injected automatically when I call new Lister(); If somebody has an answer, please let me know!
 
Rob Spoor
Sheriff
Posts: 20820
68
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
CDI never works if you treat the objects as POJOs. You need to let the CDI container manage instances, otherwise nothing will get injected. If you create instances yourself you're just on your own, CDI won't help you any more.
 
Christian Wansart
Ranch Hand
Posts: 32
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I spend some time yesterday and I guess I understand it now.
 
Rob Spoor
Sheriff
Posts: 20820
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!