Using CDI standalone

Today I will show you how to use CDI in your appplication, when you don’t have the a JEE server.

CDI is the Context and Dependency Injection, as defined in the JSR-346 (CDI 1.1) and JSR-299 (CDI 1.0). It is a powerful and lightweight mechanism that provides dependency injection, contextual lifecycles, events, decorators and interceptors.
But usually it’s used in JEE 6 / 7 environments. So I asked myself:  “Is it possible to use CDI in SE environment?
And the answer is: “Yes”. The amazing guys of JBoss created a SE variant of Weld.

In the next few minutes I will show you how to uses Weld in a standalone application.
It will be a simple Hello World example.

Preparation

Dependency

  • Group : org.jboss.weld.se
  • Artifact : weld-se
  • Version : 2.1.1.Final

beans.xml

As usual in CDI you need a empty beans.xml. In Weld SE this file must be placed in META-INF.

build script

 

That’s all.

Now hands on code

At first our HelloWorldPrinter.

As a last step, we need a class that acts a an entry point for your application. In Weld SE this is achieved by a CDI bean that observes the ContainerInitialized event.

So let’s implement the BootLoader which listens to the mentioned event. This class will have the HelloWorldPrinter as a injected dependency.

As you may have recognized I added a second parameter to BootLoader.bootListener. The second parameter injects command line arguments.

Run it!

That’s it.

The example code is available at github. This project contains also a simple example of CDI-Unit.

 
20 Kudos
Don't
move!

2 thoughts on “Using CDI standalone

  1. I found this example doesn’t work as described. With Gradle the beans.xml is copied to build/resources/main/META-INF but weld does not pick it up from there. I needed to add this to build.gradle to get it to work:

    processResources.doLast {
    copy {
    from ‘build/resources/main/META-INF/beans.xml’
    into ‘build/classes/main/META-INF/’
    }
    }

    Also, I found that if you try this with weld 2.2.8 it doesn’t work. This seems to be because that version of weld does not recognise an empty (zero bytes) beans.xml. If you replace with with some empty XML like this it works:



Leave a Reply

Your email address will not be published. Required fields are marked *