I am having some problems understanding the concept of component instantiation in iPOJO. I read this guide and I get the analogy to classes and objects but I still have some concrete problems and some conceptual problems that I hope someone can clarify
I thought I needed to create instances via iPOJO (@Instantiate or factories) only for service providers since they never use new because the impl is always hidden. However, I have some consumers @Component that I instantiate myself (say in a main() method where I call new on them directly). I made them @Component because they need to have things injected. I was assuming that the ipojo bytecode manipulation would make it so that when the objects were constructed, they would have their dependencies injected (I'm using mostly method injection with @Bind) but it seems that is not the case. Can someone clarify this to me please. Now it seems to me that for iPOJO to do any injection at all I need to always use one of the iPOJO instantiation techniques. The problem I have is that then the constructors I made in the consumer classes are not called.
This is a simplified example to illustrate my confusion
@Component(name="test")
public class MyFoo {
private List<External> externals; //injected
private Bar bar; //passed via constructor. Bar is *not* a @Component
public MyFoo(Bar otherBar) {
bar = otherBar;
externals = new ArrayList();
}
@Bind(aggregate=true)
public addExternal(External service) {
externals.add(service);
}
}
So, as can be seen here, I need to have all the providers of interface External
, but I also need a Bar
object that I pass when I construct the object using new MyFoo(someBar)
My problem is that if I need to pass a Bar
to the constructor then I need to use new; but If i use new, iPojo never invokes my injection method. On the other hand, if I use iPOJOs instantiation (say I add @Instantiate) then the injection does happen but the constructor is not invoked, so the bind throws a NPE because the list has not been created yet + bar will not be set. I know I can create the list inside the bind method, but my question is more conceptual.
- How are you supposed to accomplish this (framework injection + argument passing in the constructor)?
- How can iPOJO be calling addExternal (which means the object has been created) without calling my one and only constructor that creates the object? this is very counter-intuitive in standard java
- Are you just not supposed to use constructors when using iPOJO components maybe?