Search code examples
javacdiweldjboss-weldweld2

Is it possible to obtain a reference of containing class (CDI)?


My setup is as below -

public class ParentModel {
    private StatusModel sm;
}

StatusModel class is as below -

public class StatusModel {
    private ParentModel pm;

    public void setParentModel(ParentModel pm) {
        this.pm = pm;
    }
}

pm inside StatusModel is the reference of ParentModel instance upon which the StatusModel depends.

Inside dao - I'm injecting ParentModel as below

@Inject
private Instance<ParentModel> factory;

but, setting ParentModel reference to StatusModel using a separate method call as below -

pm = factory.get();
pm.setters...
pm.getSm().setParentModel(pm);//<----- is it possible to avoid this?

Can we obtain the pm reference inside sm without a method call?


Solution

  • Depending on which object may be, however briefly, in an incompletely initialized state, inject that object into the other one as a constructor parameter, and call the setter there. The whole object hierarchy will then be consistent when you resolve the latter object:

    class ParentModel {
        StatusModel _status;
        ParentModel(@Inject StatusModel status) {
            _status = status;
            _status.setParent(this);
        }
    }
    
    class StatusModel {
        ParentModel _parent;
        void setParent(ParentModel parent) { _parent = parent);
    }
    

    That said, I would suggest breaking this cyclic dependency up, because then you can restore a nice-to-have property of the design where it’s impossible to construct invalid objects.