0

I am trying to write a CDI extension which can customise WebServer object to programmatically generate KeyConfig. But the extension is not getting executed in the order I expect.

I wrote a extension class like below

public final class CustomWebServerExtension implements Extension {
    public CustomWebServerExtension() {}
    private void onStartup(@Observes @Priority(11) @Initialized(ApplicationScoped.class) Object event,
                   BeanManager beanManager) {
        ServerCdiExtension server = beanManager.getExtension(ServerCdiExtension.class);
        server.serverBuilder().port(9000).build();
    }
}

I am referring to https://github.com/helidon-io/helidon/issues/3727#issuecomment-993535342 to write this bean class.

When I try to run my server, I see that server.serverBuilder() is null. It seems ServerCdiExtension.startServer is getting executed before code is executed. Any pointers how I can fix this?

  • You have written a CDI portable extension, not a bean. Did you ensure it is present as a service provider under `META-INF/services`? Observer methods observing the same event with the same qualifiers with lower priorities are guaranteed by the specification to be called before higher priority ones. Your method's priority of `11` is before 4100 (`ServerCdiExtension`'s `onStartup` effective priority). The only way `serverBuilder` can be `null` is if, contrary to the specification, `ServerCdiExtension`'s `onStartup` fires first, in which case you have found a severe bug in Weld (highly unlikely). – Laird Nelson Aug 22 '23 at 21:25
  • Oh, sorry. It is a CDI Extension. I'll edit the question. Yes, I have added class it `META-INF/services`. – Pavan Vachhani Aug 23 '23 at 05:02
  • Started from basic helidon-quickstart template and it is working as expected. Thanks Laird. – Pavan Vachhani Aug 23 '23 at 08:33

1 Answers1

0

This was answered in comments, I will add a summary here.

  1. When writing an extension, it must be visible to ServiceLoader (either by creating a file META-INF/services/jakarta.enterprise.inject.spi.Extension with the implementation class a line in the file, or by using module system and adding provides Extension with CustomWebServerExtension)
  2. Make sure the imports are from the correct packages:
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.Extension;
Tomas Langer
  • 451
  • 3
  • 5