2016-02-24 44 views
0

我想使用吉斯(4.0)來引導我的可執行文件的依賴從我的主要動力類中(也許這是一個吉斯反模式?​​):注入從其他圖書館父類與吉斯

// Groovy pseudo-code 
// This Buzz class is located in a 3rd party lib that I don't have access to 
class Buzz { 
    int foobaz 
    Whistlefeather whistlefeather 

    // other stuff, include constructor, setters and getters 
} 

class MyApp extends Buzz { 
    @Inject 
    DatabaseClient dbClient 

    @Inject 
    FizzRestClient fizzClient 

    static void main(String[] args) { 
     MyApp app = Guice.createInjector(new MyAppModule()).getInstance(MyApp) 
     app.run() 
    } 

    private void run() { 
     // Do your thing, little app! 
    } 
} 

class MyAppModule extends AbstractModule { 
    @Override 
    void configure() { 
     bind(DatabaseClient).to(DefaultDatabaseClient) 
     bind(FizzRestClient).to(DefaultFizzRestClient) 

     // But how do I configure MyApp's 'foobaz' and 'whistlefeather' 
     // properties? Again, I don't have access to the code, so I 
     // can't annotate them with @Inject, @Named, etc. 
    } 
} 

所以我的問題是MyApp實際上擴展了一個生活在第三方(OSS)JAR中的基礎對象。此基類(Buzz)未設置用於Javax Inject或Guice。但我希望Guice能夠配置其foobazwhistlefeather屬性....任何想法?

回答

1

您可以在Guice模塊中使用@Provide方法創建並注入任何Bean。例如:

@Provides 
MyApp externalService(DatabaseClient dbClient, Whistlefeather wf) { 
    MyApp app = new MyApp(); 
    app.setDatabaseCLient(dbClient); 
    app.setWhitlefeature(wf); 
    return app; 
} 

@Provides

+0

感謝@Jeremie B(+1) - 你介意更新您的答案,包括我的具體使用情況(和類)?我問,因爲我不確定你是否完全明白我在問什麼(或者更可能,我只是不明白你在說什麼!)。我很擔心,因爲'MyApp'擴展了'Buzz',並且因爲'MyApp'是創建Guice注入器的地方(我的依賴圖的「根」),所以您建議的方法將不起作用... – smeeb

+1

i還沒有看到你的'MyApp'正在擴展'Buzz'。這個嗡嗡聲沒有setter? –

+0

謝謝@Jeremie B(再次+1) - 是的,它有ctor和這些屬性的getter和setter。有任何想法嗎? – smeeb