ShaggyInjun, you refer to the Initializable interface which indicates you were trying to integrate with the FXMLLoader. All of the information below assumes you are using FXML for your interface definition and only discusses issues around injecting values into FXML controllers.
The FXMLLoader
has the concept of a controller factory, which you should use to integrate the controller instantiation with your dependency injection system. There is a brief discussion of controller factories in Oracle's Mastering FXML Tutorial. Andy demonstrates definition of such a factory for Guice in his blog and there is a comprehensive integration of Guice in FXML on github.
For Weld you will need to implement a similar controller factory callback mechanism to realize the dependency injection functionality which Weld provides. The article by Matthieu Brouillard that you linked in a comment FXML & JavaFX—Fueled by CDI & JBoss Weld would seem to provide all of the information you need to both initialize Weld and interface Weld into the FXMLLoader controller factory mechanism. Specifically, the following code is the Weld equivalent of Andy Till's FXML based injection mechanism:
public class FXMLLoaderProducer {
@Inject Instance<Object> instance;
@Produces public FXMLLoader createLoader() {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(new Callback<Class<?>, Object>() {
@Override public Object call(Class<?> param) {
return instance.select(param).get();
}
});
return loader;
}
}
Even when an FXMLoader controller factory is used, I believe it is the FXMLLoader that is instantiating the controller. So in those cases, you should not make of annotations like @PostConstruct
because they only apply when the dependency injection system is maintaining the lifecycle of the object - and that is not the case if the FXMLLoader creates the controller.
There is one other alternative, and that it is to explicitly set the controller to be used by the FXMLLoader using setController. This would allow you to have your dependency injection system instantiate (and inject into) controllers using whatever means it wishes and then you could subsequently pass the instantiated controller to your FXMLLoader. In such cases anotations like @PostConstruct
should work as the dependency injection system is now maintaining the objects lifecycle (and @PostConstruct
would be invoked by the dependency injection system after the Controller has been created and before you pass the Controller through to the FXMLLoader).
I'll post Andy's Guice based solution here as it is a small and simple example of how similar injection is accomplished in Guice (in case his blog goes offline):
class GuiceControllerFactory implements Callback<Class<?>, Object> {
private final Injector injector;
public GuiceControllerFactory(Injector anInjector) {
injector = anInjector;
}
@Override public Object call(Class<?> aClass) {
return injector.getInstance(aClass);
}
}