Dependency Injection in Abstract and Concrete Classes

I am using JSF and have been running around in the problem for quite a long time, I have searched many places but did not find a suitable answer.

Can I have dependency injection working in the abstract class (or more generally the class higher in the hierarchy)? Also, how are we supposed to handle annotations when dealing with inheritance? I read that it would be common practice not to annotate an abstract class, but only a concrete one, but then that would not imply injection for that abstract one?

My problem is that one (check the last comment):

Abstract class

@ManagedBean
@ViewScoped
public abstract class AbstractController<T extends VersionedObject> implements Serializable {
    @ManagedProperty("#{libraryVersionController}")
    private LibraryVersionController libraryVersionController;

public List<T> loadFromDatasource(IVersionedServiceBase<T> service) {
        log.info("Loading generic VO from data source");

        VersionedObjectFilter filter = new VersionedObjectFilter();
        filter.setSelectedLibVersion(libraryVersionController.getSelectedItem());
        // etc
    }
    // getters, setters...
}

      

Concrete class

@ManagedBean
@ViewScoped
public class DomainController extends AbstractController<Domain> implements Serializable {
private List<Domain> allItems;
   private Domain[] selectedItem;

   @ManagedProperty(value = "#{domainService}")
   private DomainService domainService;

   @PostConstruct
   public void loadFromDatasource() {
    allItems = super.loadFromDatasource(domainService);
        // !! DOES NOT WORK, null pointer exception on abstract class (libraryVersionController)
   // etc
}

      

The getters and setters are set up correctly, as I could read in my .xhml, this is the specific class I reference (# {domainController.allItems}), there is only one @PostConstruct. I am using JSF2.1 and Mojarra.

Thank you for your help!

+3


source to share


1 answer


As for your NullPointerException, I assume the AbstractController.setLibraryVersionController is missing. As I understand it, when the AbstractController is constructed (presumably it has an implicit constructor, although it is abstract), this method is needed to populate the corresponding value.

I know you said that all getters and setters are there, but that seems complicated, so maybe you missed it. If you add an entry to this method, you can check if JSF is trying to populate this value and also check if the value is null or not.



For a general question about how dependency injection works with inheritance hierarchy, I would assume that your approach is fine and that dependencies are injected for the base class and then for the derived class along the chain.

0


source







All Articles