Weld in Java SE

Posted by    |       CDI Weld

One of the really nice things about Weld is how nicely it works in Java SE. Of course, if you run Weld on its own, you won't get nice functionality like EJBs (you'll need an embeddable EJB container for that), but you do get a bunch of great stuff, including:

  • Managed beans with @PostConstruct and @PreDestroy lifecycle callbacks
  • Dependency injection with qualifiers and alternatives
  • @ApplicationScoped, @Dependent and @Singleton scopes
  • Interceptors and decorators
  • Stereotypes
  • Events
  • Portable extension support

The Weld distribution comes with an example console application, and an example Swing application.

Here's a very simple console application:

public class HelloWorld {

    void init() {
        System.out.println("Initializing Hello World application");

    void printHello(@Observes ContainerInitialized event, 
                    @Parameters List<String> parameters) {
        System.out.println("Hello " + parameters.get(0));


The printHello() method is a CDI observer method for the ContainerInitialized event. This event is fired by the Weld Java SE extension when the console application starts. The command line parameters are available for injection using @Parameters List<String>.

As usual, we need a file named META-INF/beans.xml the the jar or classpath directory containing our HelloWorld class.

We run the application using:

java org.jboss.weld.environments.se.StartMain Gavin

Of course, if you're using CDI you probably want to make much more use of dependency injection, for example:

public class HelloWorld {

    void printHello(@Observes ContainerInitialized event, 
                    @Parameters List<String> parameters, 
                    Hello hello) {


Where Hello is a bean:

public class Hello {
    public void say(String name) {
        System.out.println("Hello " + name);

The Weld SE extension was created by contributor Peter Royle.

Back to top