0

I am using FXML and Weld SE together. So far it works well except for certain cases.

public class ApiController extends AnchorPane implements Initializable {

    @Inject
    private ApiFactory        apiFactory;
    @FXML
    private TextArea          requestArea;
    @FXML
    private TextArea          responseArea;

    public ApiController() {
        // creates FXML loader, sets weld controller factory, and assigns "this" to root/controller.
        ControlCenter.loadFxml("/view/api.fxml", this);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // breakpoint here will show "apiFactory" null
    }

}

I need to do initialization but only after Weld has injected ApiFactory implementation. The injection occurs, however, after initialize is called. How can I initialize my class after Weld injects my dependency?

user2914191
  • 877
  • 1
  • 8
  • 21
  • 2
    Since you are calling the `FXMLLoader#load` in your constructor, the `initialize` method is called before the constructor returns, and thus before Weld has a chance to inject anything. Looking at [the documentation](https://docs.jboss.org/weld/reference/latest/en-US/html/injection.html#_injection_points), it appears you should either inject required parameters as constructor parameters, or else move all code that relies on injected values to a `@PostConstruct` annotated method. – Itai Sep 04 '17 at 09:24
  • 1
    Try moving `ControlCenter.loadFxml("/view/api.fxml", this);` into initializer method. E.g. method which will have `@Inject` on it and will be executed right after the bean is constructed by CDI (therefore you should have everything injected by then). Read up here for more info - http://docs.jboss.org/cdi/spec/1.2/cdi-spec.html#initializer_methods – Siliarus Sep 04 '17 at 09:31
  • looks like `@PostConstruct` is what needs to be done – user2914191 Sep 04 '17 at 17:01
  • the `@PostConstruct` is fired before the field is injected. using initializer method works – user2914191 Sep 04 '17 at 17:12

0 Answers0