0

我有一堆動物的對象,例如:注入對象的列表在我的項目中發揮應用程序上下文

他們中的一些有依賴注入:

class Monkey @Inject() (wsClient: WSClient, configuration: Configuration) extends Animal { 
    ... 
} 

,有些不是:

class Giraffe extends Animal { 
    ... 
} 

在我AnimalsService類,我需要所有的動物對象實例的列表,

目前我的服務是越來越的人的名單作爲一個依賴注入:

class AnimalsService @Inject() (animals: List[Animal]) { 
    // here I can use animals as my desire 
} 

,然後我結合它綁定類:

class Bindings extends AbstractModule { 
    override def configure(): Unit = { 
    bind(classOf[AnimalsService]).toProvider(classOf[AnimalServiceProvider]) 
    } 
} 

object Bindings { 
    class AnimalServiceProvider @Inject() (giraffe: Giraffe, monkey: Monkey ...) extends Provider[AnimalsService] { 
    override def get: AnimalsService = { 
     new AnimalsService(List(giraffe,monkey...)) 
    } 
    } 
} 

這工作完全,但我會preffer是要以某種方式將該列表添加到我的應用程序上下文作爲應用程序加載,所以我不需要這樣做......

這個當前的解決方案還意味着我需要添加新動物到AnimalServiceProvider構造函數,並在這裏新每一個我需要一種新的動物,並且這種情況會不斷髮生...

什麼是處理這種情況的最佳方式?

我想,也許使用@Named註釋吉斯的,但不知道它的正確的方式或如何命名對象這樣的列表...

回答

0

我會做一個Singleton豆具有列表和方法添加定義

class AnimalsService @Inject()() { 
    val animals: List[Animal] 
    def addAnimal(animal: Animal) { 
     .... 
    } 
    // here I can use animals as my desire 
} 

然後需要的動物需要一個額外的單與Eager bindings

class MonkeyConfigurator @Inject() (animalsService: AnimalsService) extends Animal { 
    animalsService.add(this) //Or anything 
    // here I can use animals as my desire 
} 
+0

只是快速的想法中的每個模塊中,有這麼我的詳細信息丟失了,生病後試圖補充我回家後。 – rekiem87

相關問題