Java EE 6 Injection Into Abstract Class

rusty_turkey picture rusty_turkey · May 2, 2012 · Viewed 10.7k times · Source

In a Java EE 6 project I am working on, there is a lone field annotated with @EJB that is not being injected. Injection is working fine everywhere else.

Being new to Java EE, I don't know if it is related to the field being in an abstract class, nor can I find any output from Glassfish (3.1.2) about why this injection is not occurring.

There are no errors or warnings in the server log until the NullPointerException occurs because the dataSourceControl field is null. I have verified that the DataSourceControl Singleton is being instantiated by putting logging in it's constructor.

As far as I can tell, the dataSourceControl field is not being injected, but the logs give me no reason why this is.

public abstract class AbstractDataMap<T> {
  @EJB
  private DataSourceControl dataSourceControl; // This is not being injected

  DataSourceControl getDataSourceControl() {
    return dataSourceControl;
  }
  // Other methods
}

public abstract class AbstractDataMapDBProd<T> extends AbstractDataMap<T> {
  @Override
  protected Connection getDBConnection() {
    return getDataSourceControl().getConnectionX(); // NullPointerException here
  }
  // Other methods
}

@Stateless
public class CountryMap extends AbstractDataMapDBProd<Country> {
  public boolean update(final Country current, final Country legacy) {
    Connection connection = getDBConnection();
    // More code 'n stuff
  }
}

Are there any rules I have missed regarding injection that is defined in an abstract class?

Anything else that cries 'noob'?

If there are no obvious errors, any ideas on how to debug this?

Answer

Brett Kail picture Brett Kail · May 3, 2012

Injection will work in any class (base class, superclass, abstract superclass, etc.). However, injection will only work so long as you obtain an instance of CountryMap from the container (i.e., injection or lookup) rather than via new CountryMap. How are you obtaining an instance of CountryMap?