I've been tasked to refactor an old application, which used to create DAO's all over the place, by using the new keyword, and local managed entitymanager.
Now I'm supposed to use JTA to manage the connections. For what I can understand, I should use CDI for that. So far it haven't been a problems. My views are CDI views, and i @Inject all my DAO's, or in other cases whole controllers that use the DAO's, like the following example.
@CDIView(value = TestView.VIEW_ID)
public class TestView extends Test implements View {
public static final String VIEW_ID = "testviewer";
@Inject
private
TestInterface testInterface;
public void viewLogic() {
...
}
While all this works fine, I'm starting to get worry. Because behind the scenes there is a lot of threads, running simultaneously. These threads would need their own instances of objects, and therefore just cannot be injected - or can they? An example would be:
@Stateless
public class TestInterface {
@Inject
TestDAO testDAO;
private List<TestRunner> getTestRunners(Test test, ToplevelTest tlt){
List<TestRunner> runners = new ArrayList<>();
for(SomeThing st : getTestSomethings()){
if(st.condition())
runners.add(new AbstractTestRunner());
else runners.add(new FancyTestRunner());
}
}
private SomeDataAccess(){
testDAO.save(new Test());
}
This example code would the execute within a managed bean, which is fine (I think!), but these testrunners would also need to have access to the dataccesslayer. But I need (a variable) multiple instances of these.
I've read that you can use CDI.current().get(MySingletonClass.class) Is it a good idea (and possible?) to obtain a singleton repository to use as dataccess within these testrunners, and then just "new" the testrunners as before?
Or is there a better way to handle all this?
All suggestions are warmly received. I'm rather new to CDI.
Best regards
You could use the more "primitive" method of dependency injection, pass an instance of MySingletonClass
into the TestRunners constructor.