简体   繁体   English

对运行时生成的依赖项使用 spring 依赖注入

[英]using spring dependency injection for runtime generated dependencies

I am new to Spring and to better understand what I'm learning, I decide to integrate Spring into one of my projects.我是 Spring 的新手,为了更好地了解我正在学习的内容,我决定将 Spring 集成到我的一个项目中。 In the project, a collection of Events is generated at runtime, where Event is a POJO.在项目中,运行时会生成一个Events的集合,其中Event是一个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. FetcherA 和 FetcherB 是两个依赖于一个 Event 实例来获取其输出的类,这意味着 FetcherA 和 FetcherB 的输出对于不同的 Event 实例是不同的。

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.由于这些事件是在运行时生成的,我如何使用 Spring 依赖注入将事件 bean 注入到每个在运行时创建的 FetcherA 和 FetcherB 对象中。 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);
   });

} ```

In your use case, none of Event , FetcherA , or FetcherB should be Spring-managed, ie they should not be Spring beans.在您的用例中, EventFetcherAFetcherB都不应该是 Spring 管理的,即它们不应该是 Spring bean。

If you moved the Fetch field to be a parameter to the fetch() method, that would allow both FetcherX classes to be singleton beans.如果您将Fetch字段移动为fetch()方法的参数,这将允许FetcherX类成为单例bean。

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.您可以坚持,在这种情况下FetcherX类将是原型bean,并且您的代码将与 spring 容器集成以在循环内请求新实例。 Not really optimal.不是很理想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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