Java EE 6 @Inject lazy? [duplicate]
Asked Answered
A

1

5

I am doing some refactoring and reviewing of the application that we are currently developing. While doing this I found that more beans are injected and I think making they loading in an lazy manner would be better suited for their purpose. I am using Java EE 6 and tend to use more CDI than EJB injection.

So the question is whether it is possible to inject the beans lazily and if so, how can you do it?

Abominate answered 10/4, 2013 at 8:32 Comment(1)
yes, that pretty much answers my question - it's not possible. Thank you!Abominate
B
13

What about using

@Inject
private Instance<?> lazyProvider;

?

That allows Getting instance of "?" when actually needed via

lazyProvider.get();
Boehmenism answered 11/4, 2013 at 5:22 Comment(4)
I have to try it, sounds promising. And how do I say what type I want to get?Abominate
Instance is a generic type. So when you inject an Instance<Foo>, get() will return a Foo.Boehmenism
Ok, how do I inject Foo for instance? Where do I decide what to inject?Abominate
Just like you would do with Foo itself. By default, you will get a new instance with dependent scope. But you could also (by using a producer or annotating the Foo.class) define custom scope and injection behavior.Boehmenism

© 2022 - 2024 — McMap. All rights reserved.