using spring dependency injection for runtime generated dependencies

Tags: , , , ,



I am new to Spring and to better understand what I’m learning, I decide to integrate Spring into one of my projects. In the project, a collection of Events is generated at runtime, where Event is a POJO. FetcherA and FetcherB are two classes that depended on an Event instance to fetch their output, which means the output of FetcherA and FetcherB is different for different Event instances.

Since these Events are generated at runtime, how can I use Spring dependency injection to inject an event bean into every FetcherA and FetcherB object created at runtime. Below is an example of what my code looks like.

public class Event {
     //some data fields
}

public class FetcherA {
    private Event event;

    FetcherA (Event event) {this.event=event}
    
    public String fetch () {//fetch output based on this event}
}

public class FetcherB {
    private Event event;

    FetcherB (Event event) {this.event=event}
    
    public String fetch () {//fetch output based on this event}
}

public static void main (String[] args) {
   List<Event> events = EventsFetcher.fetchEvent();
   List<String> myTextBook = new ArrayList<String>();
   events.forEach ( event -> {
      String messageBody= new FetcherA (event).fetch();
      String messageTitle = new FetcherB (event).fetch();
      myTextBook.add(messageBody);
      myTextBook.add(messageTitle);
   });

} ```

Answer

In your use case, none of Event, FetcherA, or FetcherB should be Spring-managed, i.e. they should not be Spring beans.

If you moved the Fetch field to be a parameter to the fetch() method, that would allow both FetcherX classes to be singleton beans.

You could insist, in which case the FetcherX classes would be prototype beans, and your code would integrate with the spring container to ask for new instances inside the loop. Not really optimal.



Source: stackoverflow