How to properly use Weld in JavaFX 2 application?



I’m trying to get Weld to work inside my JavaFX 2 (SE) application (or should I say JavaFX inside Weld?). I have controllers which respond to user interaction. Now I would like to inject my services like a database service for example into these controllers.

Using Weld this should be as easy as :

private MyService service;

Now in order to initialise Weld there are three options.
Option 1)

public void main(@Observes ContainerInitialized event) {
    launch(); // start JavaFX

Option 2)

public static void main(final String[] args) {
    new StartMain(args).go();

Option 3)

public static void main(final String[] args) {
    final WeldContainer weld = new Weld().initialize();
    service = weld.instance().select(MyService.class).get();

Option 1 and 2 lead to NullPointerExceptions in my controllers because nothing is injected at the annotated injection points. Only option 3 works but this is not really what I need because I do not want the service in my main application class but in my JavaFX controllers instead. With option 3 I would have to pass the initialized service to my controller classes somehow and in this case I do not need Weld. So how do I inject service beans into JavaFX controllers? Unfortunately I found no documentation about my issue.

Maybe someone has gathered experience using Weld and JavaFX and can help me out.


I wrote down some of my efforts in the Weld discussion forum but I got no answer unfortunately. In my opinion Weld does not work with JavaFX. I think I have to insert my services into my controllers using good old setters (see the forum for a solution).

Update 2

I found a blog about Weld and JavaFX 2. I have not tried the solution yet but I think it’s useful for other programmers.






Facebook Comments

Post a comment