OpenLiberty / open-liberty

Open Liberty is a highly composable, fast to start, dynamic application server runtime environment
https://openliberty.io
Eclipse Public License 2.0
1.15k stars 589 forks source link

CDI Injection not working in servlet filters with a simple servlet application #26042

Open fmhwong opened 1 year ago

fmhwong commented 1 year ago

Running a simple servlet with mpTelemetry-1.0 feature. There are no CDI beans in the application.

A servlet filter is registered programmatically with ServletContainerInitializer.onStartup(). The injection constructor wasn't called.

    @Inject
    public TelemetryServletFilter(OpenTelemetryInfo otelInfo) {
    ...
    }

Alternatively, using the following line in the init() of the servlet filter.

    OpenTelemetryInfo itelInfo = CDI.current().select(OpenTelemetryInfo.class).get();

and it failed with

[ERROR   ] SRVE0315E: An exception occurred: java.lang.Throwable: jakarta.servlet.ServletException: Filter [io.openliberty.microprofile.telemetry.internal.rest.TelemetryServletFilter]: could not be initialized
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:5137)
    at [internal classes]
Caused by: jakarta.servlet.ServletException: Filter [io.openliberty.microprofile.telemetry.internal.rest.TelemetryServletFilter]: could not be initialized
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.init(FilterInstanceWrapper.java:159)
    ... 1 more
Caused by: java.lang.IllegalStateException: Could not find deployment
    at com.ibm.ws.cdi.impl.AbstractCDIRuntime.getCDI(AbstractCDIRuntime.java:163)
    ... 1 more

Both of the above work when running with a JAX-RS application.

Azquelt commented 1 year ago

CDI is disabled for performance reasons if there are no beans or extensions in the application.

Therefore, servlet filters (or any other EE component) registered by liberty features must not depend on CDI being enabled unless they can guarantee that the application will contain at least one bean.

Azquelt commented 1 year ago

This has the same cause as #26043