How to implement a command template via CDI?

I am new to CDI and a little confused. I have the following problem. We have an Action class. And we have a wrapper class that stores all Action objects in hashmap. Something like that.

class TestAction implements Action{
  @EJB
  private MyBean bean; 
  public void doSomething(){
    //here we do something with injected EJB
  }
}

class Foo {
   private HashMap<String, Action> hm;
   public void execute (String action){
   this.hm.get(action).doSomething();    
 }    
}

When I do not use CDI - everything is all right. But I need to use it. Therefore, as I understand it, I have to create all my actions using the cdi container, otherwise the CDI container will not be able to inject managed beans into them. So my question is: what is the best way to implement a command template via CDI?

: " " Dhanji R. Prasanna, Weld-reference (WR), JavaEE7 ( CDI) - . , , HashMap. , , . . . . :

@ApplicationScoped
public class ActionMapFactory {
    @Produces @Preffered
    public HashMap<String, Action> getHashMap(){
    HashMap<String, Action> hm=new HashMap<>();
     if (...){
     hm.put("save",new SaveAction());
     }
     return hm;
    }
}

WR:

. Java. , .

WR, , Foo?

+3
1

new, ActionMapFactory HashMap :

@ApplicationScoped
public class ActionMapFactory {

    @Inject
    private SaveAction saveAction;

    @Inject
    private DeleteAction deleteAction;

    // And so on

    @Produces @Preffered
    public HashMap<String, Action> getHashMap() {
        Map<String, Action> hm = new HashMap<>();
        hm.put("save", saveAction);
        hm.put("delete", deleteAction);
        return hm;
    }
}

Action , :

private Map<String, Action> actionMap;

// This is part of the CDI bean contract
protected ActionMapFactory() {}

@Inject
public ActionMapFactory(SaveAction saveAction, DeleteAction deleteAction) {
    actionMap = new HashMap<>();
    actionMap.put("save", saveAction);
    actionMap.put("delete", deleteAction);
}

@Produces @Preffered
public HashMap<String, Action> getHashMap() {
    return actionMap;
}
+1

All Articles