Using CDI Beans in JBoss – WildFly modules

The building blocks of the application server are modules which are, often, Java libraries which can be run out of the application server context. It is however possible to deploy CDI Beans or use AS Resources in your modules. Let’s see how.

In our example project, we will use a Java class which contains CDI annotations so that the Container will be in charge to create instances of it, moreover our class uses @Resources which are defined into the application server:

Here is our DemoBean class, that is @ApplicationScoped :

package democdi;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.sql.*;

public class DemoBean {
	public void init() {
		System.out.println("init CDI DemoBean");

	@Resource(name = "java:jboss/datasources/ExampleDS")
	private DataSource dataSource;

	public String doSomething() {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String time = null;
		try {
			conn = dataSource.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT CURRENT_TIME() ");;
			time = rs.getString(1);

		} catch (SQLException e) {

		} finally {
			try {
			} catch (Exception e) {	}

			try {
			} catch (Exception e) {	}
			try {
			} catch (Exception e) {	}

		return time;


 Installing this class as a module is just a matter of specifying the correct dependencies in your module.xml:

<module xmlns="urn:jboss:module:1.1" name="com.democdi" >
        <resource-root path="cdibean.jar"/>

        <module name="javax.api"/>
        <module name="javax.annotation.api"/>
        <module name="javax.ejb.api"/>
        <module name="javax.resource.api"/>
        <module name="javax.enterprise.api"/>
        <module name="javax.inject.api"/>
        <module name="javax.interceptor.api"/>
        <module name="javax.validation.api"/>
        <module name="org.hibernate.validator"/>
        <module name=""/>


So, assumed that your Bean is packaged in a cdibean.jar file, we have included dependencies to some required Java EE core API. We also need to package a beans.xml file in the META-INF folder of your cdibean.jar. This picture shows the structure of our module:

cdi beans jboss tutorial

 That’s all! Now you can safely inject your DemoBean in your applications:

@Inject   DemoBean demo;

 Don’t forget that your module needs to be referenced in the applications which are using it! Here is a sample jboss-deployment-structure.xml file:


			<module name="com.democdi" export="true" meta-inf="import" />