Inject new objects in for loop with CDI (Weld)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Inject new objects in for loop with CDI (Weld)



I want to introduce CDI to existing project. Currently we are creating new objects inside for loop like


Context context;
for(String string : strings) {
context = new Context();
// do some operations with string.
// set outcomes of above operation in context.
}



Now if I am injecting Context as


Context


@Inject Context context;



I'm getting same instance every time.



I'm wondering if there is any way available in CDI to create new Context inside loop?


Context





Why would you need that? You are trying to abuse the dependency injection mechanism.
– Adrian Mitev
Oct 3 '14 at 19:35





Hi Adrian, do you think it would be a design approach. Although its a use case requirement, but before opting for it, I would definitely like to see if its a kind of anti pattern? Thanks, Raman
– Raman
Oct 4 '14 at 19:34






1 Answer
1



As long as you do not use special scopes, you can use


@Inject
Instance<B> bProvider;

...
B b = bProvider.get();



and you will get a new "B" everytime. Check out this gist.





To clarify, B must be annotated as @Dependent or not annotated at all in EE 6/7 (in 7 with bean discovery all)
– John Ament
Oct 4 '14 at 13:37


B


@Dependent






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results