Skip to content

CDI (Contexts and Dependency Injection)

Inject Jakarta EE predefined beans and JNDI resources, and define string resources in GlassFish with asadmin or domain.xml.

3 min readUpdated

Contexts and Dependency Injection (CDI) is the Jakarta EE (formerly Java EE) standard for injecting beans into each other. Alongside it, resource injection with @Resource injects objects from the JNDI namespace. This note lists the predefined beans the platform provides, shows resource injection of a data source, and walks through a complete example: configuration values stored as JNDI resources in GlassFish and injected into an application-scoped bean.

Inject predefined beans

Jakarta EE provides predefined beans for common platform objects. Some are injected as resources with @Resource, others as CDI beans with @Inject:

Predefined bean Resource or CDI bean Injection example
UserTransaction Resource @Resource UserTransaction transaction;
Principal Resource @Resource Principal principal;
Validator Resource @Resource Validator validator;
ValidatorFactory Resource @Resource ValidatorFactory factory;
HttpServletRequest CDI bean @Inject HttpServletRequest req;
HttpSession CDI bean @Inject HttpSession session;
ServletContext CDI bean @Inject ServletContext context;

Predefined beans are injected with dependent scope and the default qualifier @Default. An injected Principal always represents the current caller at the time it is used, not the caller at injection time.

Inject resources from JNDI

Resource injection injects any resource available in the JNDI namespace, such as data sources, connectors or custom resources, into a container-managed object: a servlet, an enterprise bean or a managed bean.

This servlet gets the platform’s default data source, which in GlassFish points to the bundled Apache Derby (Java DB) database:

public class MyServlet extends HttpServlet {
@Resource(name = "java:comp/DefaultDataSource")
private javax.sql.DataSource dsc;
// ...
}

The example uses the Java EE javax packages; on Jakarta EE 9 and later the annotation is jakarta.annotation.Resource.

Read configuration from JNDI resources

Configuration values such as an API key can live in the application server instead of the application. The server stores them as JNDI resources, and the application injects them by name.

Inject the values

The lookup attribute of @Resource names an existing JNDI entry. This application-scoped bean injects two string resources and exposes them as key/value pairs. LLMConfig is the application’s own configuration base class, not a platform type.

JndiLLMConfig.java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@ApplicationScoped
public class JndiLLMConfig extends LLMConfig {
@Resource(lookup = "java:global/llm.api.key")
private String apiKey;
@Resource(lookup = "java:global/llm.model")
private String model;
private Map<String, String> properties;
@PostConstruct
public void init() {
properties = new HashMap<>();
properties.put("llm.api.key", apiKey);
properties.put("llm.model", model);
}
@Override
public Set<String> getPropertyKeys() {
return properties.keySet();
}
@Override
public String getValue(String key) {
return properties.get(key);
}
}

The injected fields are set before @PostConstruct runs, so init() can copy them into the map.

Create the resources with asadmin

In GlassFish, a string resource is a custom resource whose factory, PrimitivesAndStringFactory, returns the value property. Create one for each value:

Terminal window
asadmin create-custom-resource \
--restype java.lang.String \
--factoryclass org.glassfish.resources.custom.factory.PrimitivesAndStringFactory \
--property value=YOUR_API_KEY \
java:global/llm.api.key
asadmin create-custom-resource \
--restype java.lang.String \
--factoryclass org.glassfish.resources.custom.factory.PrimitivesAndStringFactory \
--property value=gpt-4 \
java:global/llm.model

Or define them in domain.xml

The same resources can be written into the <resources> section of the domain’s domain.xml:

domain.xml
<custom-resource
jndi-name="java:global/llm.api.key"
res-type="java.lang.String"
factory-class="org.glassfish.resources.custom.factory.PrimitivesAndStringFactory">
<property name="value" value="YOUR_API_KEY"/>
</custom-resource>
<custom-resource
jndi-name="java:global/llm.model"
res-type="java.lang.String"
factory-class="org.glassfish.resources.custom.factory.PrimitivesAndStringFactory">
<property name="value" value="gpt-4"/>
</custom-resource>

Restart the domain so it reads the edited file:

Terminal window
asadmin restart-domain

References

Related notes

4 min read

Jakarta EE

Jakarta EE 10 and 11: component versions, deployment descriptor headers, Faces namespaces and a multi-module project layout.

  • Java & Jakarta EE
13 min read

Jakarta Faces (JSF)

Jakarta Faces (JSF) recipes: WebSocket push, validators with injection, resource handling, component binding, java.time and scopes.

  • Java & Jakarta EE
  • Web & Frontend
3 min read

JasperReports

JasperReports tips: localise reports with resource bundles, print page X of Y, control band splitting and page breaks, and float elements.

  • Java & Jakarta EE

Type to search the whole site.