简体   繁体   中英

How to register and run all implementations of a single interface using Micronaut?

Let's say that I have a simple interface:

public interface Event {
    void execute(SomeClient client);
}

And I have 5 classes implementing this interface, for example:

public class FirstEvent implements Event {
    @Override
    public void execute(SomeClient client) {
        //do various things here
        client.registerEvent(someData)
    }

What I would like to achieve is to run the execute(SomeClient client) method of all 5 implementations of Event interface during application startup.

I allready have the code that is starting up all the events I need, but I would like to separate those events to multiple classes and have a single point of executing those events. I thought of creating an Event interface, and make multiple implementations having Micronauts @Singleton annotation, so I can simply register them all without having to add them one by one to the class that is currently executing them one by one.

Is this interface solution a good decision? Is there a better way of doing this? What is a best way to achieve what I want (running ALL the classes with a single method instead of running them one by one)?

Is this interface solution a good decision?

It is.

Is there a better way of doing this?

In general, no.

What is a best way to achieve what I want (running ALL the classes with a single method instead of running them one by one)?

There isn't an objectively "best" way because you could optimize for different goals using different techniques. One option is you could inject all of the Event beans into something that will invoke the execute method on all of them.

@Singleton
public class SomeBean {
    private List<Event> events;

    public SomeBean(List<Event> events) {
        this.events = events;
    }

    // In this class you have all of the `Event`.
    // it is not clear from the question where the
    // SomeClient instance comes from, but once
    // you have that you could iterate over all
    // of the events and pass the client to the
    // execute method on each Event.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM