@Inject
void setSomething(@Optional Something something) {
// do something with something
}
}
I want this method to be called only if I've placed something in the context to be injected. Trouble is, when I construct a MyClass, a Something gets constructed to satisfy the injection. That's not what I want. How can I make this truly optional so that DI won't default construct something in order to call it? I'd settle for a call to setSomething(null).
I also saw this "strange" behavior when Something has a default
constructor. Is this the case for you as well? I need to talk to Oleg to
find out why this happens and will follow up with you one I know more.
Tom
Am 02.10.11 02:03, schrieb grillo321:
> I've got a method:
>
> class MyClass {
>
> ..
>
> @Inject
> void setSomething(@Optional Something something) {
> // do something with something
> }
>
> }
>
> I want this method to be called only if I've placed something in the
> context to be injected. Trouble is, when I construct a MyClass, a
> Something gets constructed to satisfy the injection. That's not what I
> want. How can I make this truly optional so that DI won't default
> construct something in order to call it? I'd settle for a call to
> setSomething(null).
Thanks for the reply Tom. Of course now I can't reproduce the problem, but I think the times I've seen it have involved a default constructor or at least a constructor that can be injected successfully.
And I've got another question about how @Optional is supposed to work.
I would expect that the call wouldn't be made if there's no SomeClass in the context. What I see is that the call is made but null is passed in. This is the same result as putting the @Optional on the parameter. Or putting it in both places for that matter.
Is this working as intended?
What's the best place to find doc on how this should work?