quarkuscdieager-loading

How to make a CDI bean eagerly initialized in Quarkus app


There is the project with quarkus 1.2.1 + jakarta cdi 2.0.2. I've added a listener for SQS messages. The problem is that all the beans are created lazily by default that is obviously not suitable for the listener. How to make this specific bean being initialized on application startup? Unfortunately there is not @StartUp in this jakarta version. Are there any ways to do it?

        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-universe-bom</artifactId>
            <version>1.2.1.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

enter image description here

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import java.util.Map;

@ApplicationScoped
@Named("customListener")
public class CustomListener implements MessageListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomListener.class);
    private final CustomService customService;

    @Inject
    public CustomListener(
            @Named("customService") CustomService  customService) {
        this.customService = customService;
    }

    @Override
    public void onMessage(Message message) {
        final SQSTextMessage sqsMessage = (SQSTextMessage) message;
        //bla bla bla
    }
}

Solution

  • CDI does not provide an out-of-the-box way to "eagerly" initialize beans.

    Quarkus has a specialized @Startup annotation (quarkus.io) since version 1.3.0.Final to achieve what we want.

    With CDI 4.0, the Startup event (jakarta.ee) was introduced. With this, we can enforce the creation of beans by observing the event from within the bean:

    @ApplicationScoped
    @Named("customListener")
    public class CustomListener ... {
        ...
        public void eagerInit(@Observes Startup unused) {
        }
        ...
    }
    

    Thanks to Ladislav Thon, who provided the code sample for CDI 4.0 in zulip (quarkusio.zulipchat.com).