6

I try to @Inject a field (its a jar module, empty beans.xml is existing under META-INF) like this:

IDataProvider Interface

public interface IDataProvider {
  void test();
}

DataProvider implementation import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class DataProvider implements IDataProvider {
  private int i;

  public DataProvider() {
    i = 42;
  }

  @Override
  public void test() {

  }
}

And the class where i try to inject the DataProvider

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class DataController {

  @Inject
  private IDataProvider dataProvider;

  private int k;

  public DataController() {
     k = 42;
  }
}

If i run this on Wildfly the injected dataProvider is always null (Breakpoint at DataController constructor).

On every tutorial it's done like this, so i thought this should work. Only difference is that both classes should be @ApplicationScoped

I am using Wildfly 8.2Final, Gradle, IntelliJ. My gradle.build looks like this:

apply plugin: 'java'

repositories {
  mavenCentral()
  jcenter()
}

dependencies {
  compile group:'javax', name:'javaee-web-api', version:'7.+'
  compile group:'org.jboss.ejb3', name:'jboss-ejb3-ext-api', version:'2.+'
}

sourceSets {
  main {
      java {
          srcDir 'src/api/java'
          srcDir 'src/main/java'
      }
  }

  test {
      java {
          srcDir 'src/test/java'
      }
  }
}

jar {
  from ('./src') {
      include 'META-INF/beans.xml'
  }
}

Does anyone have an idea why this is not working? i dont get any error or exception from Wildfly.

Ben1980
  • 186
  • 1
  • 3
  • 15
  • 1
    As far as I know, field injection is performed after the constructor call. You may verify this by adding a @PostConstruct annotated method and then debugging into it. – Christoph Giesche May 13 '15 at 11:39
  • How could CDI inject a field of your object before the object is constructed? The injection will happen *after* the constructor invocation. – JB Nizet May 13 '15 at 11:41
  • Someone marked this as duplicate..... but then where is the original? – Alkanshel Dec 26 '18 at 21:44

1 Answers1

12

During the construction of the DataController, it's normal the dataProvider is null. Injection happens after that.

You should add a @PostConstruct method to check for nullity of the field:

@PostConstruct
void init() {
    // dataProvider should not be null here.
}

Aditionally, error reporting on Weld is pretty well done. So you should have an explicit and detailed error message if the injection fails, and not only a null field.

Benjamin
  • 1,816
  • 13
  • 21