Does CDI work for regular Java application?

The following example works for CDI 2.

<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-core</artifactId>
    <version>3.1.2.Final</version>
</dependency>

Dependency is the same.

package com.zetcode;

import com.zetcode.provider.HelloMessageProvider;
import com.zetcode.renderer.ConsoleMessageRenderer;
import com.zetcode.renderer.MessageRenderer;

import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;

public class CdiSimple {

    public static void main(String[] args) {

        SeContainerInitializer initializer = SeContainerInitializer.newInstance();

        try (SeContainer container = initializer.disableDiscovery()
                .addBeanClasses(HelloMessageProvider.class, ConsoleMessageRenderer.class).initialize()) {

            MessageRenderer messageRenderer = container.select(ConsoleMessageRenderer.class).get();
            messageRenderer.render();
        }
    }
}

We use SeContainerInitializer and SeContainer to set up CDI on Java SE.

package com.zetcode.provider;

public interface MessageProvider {

    String getMessage();
}

This is MessageProvider.

package com.zetcode.provider;

public class HelloMessageProvider implements MessageProvider {

    public String getMessage() {

        return "Hello there";
    }
}

This is HelloMessageProvider.

package com.zetcode.renderer;

public interface MessageRenderer {

    void render();
}

This is MessageRenderer.

package com.zetcode.renderer;

import com.zetcode.provider.MessageProvider;

import javax.inject.Inject;

public class ConsoleMessageRenderer implements MessageRenderer {

    @Inject
    private MessageProvider messageProvider;

    public void render() {

        var message = messageProvider.getMessage();

        System.out.println(message);
    }
}

And finally, this is ConsoleMessageRenderer.


It is possible to use CDI in a standalone application.

Weld weld = new Weld();
WeldContainer container = weld.initialize();
World helloWorld = container.instance().select(World.class).get();
System.out.println(helloWorld.helloWorld());
weld.shutdown();

You will also need the weld-se dependency.

<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-core</artifactId>
    <version>2.2.4.Final</version>
</dependency>

See also Weld documentation on the subject.

Tags:

Java

Cdi