If you are working with a Java EE 6+ application server, CDI is part of the container and you do not need to do anything to start using it. But CDI is not limited to Java EE application servers. It can be used in Java SE applications or simple servlet containers just as easily. Let's take a look at using CDI in a simple command-line application.
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>3.0.0.Alpha15</version>
</dependency>
CDI requires an empty beans.xml file so it can scan the JAR for classes. So create
src/main/resources/META-INF/beans.xml
with the following
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
<scan>
<exclude name="org.jboss.weld.**" />
</scan>
</beans>
In this example, the main(String []) method initializes CDI and then CDI is used to get an instance of the class itself to start running the SE application.
import java.util.Arrays;
import java.util.List;
import javax.enterprise.inject.spi.CDI;
import javax.inject.Inject;
public class Main {
public static void main(String[] args) {
CDI<Object> cdi = CDI.getCDIProvider().initialize();
Main main = cdi.select(Main.class).get();
main.main(Arrays.asList(args));
}
@Inject
protected MyService myService;
protected void main(List<String> args) {
System.out.println("Application starting");
// MyService object injected by CDI
myService.go();
}
}
That's it, really simple.