簡體   English   中英

使用Guice從其他庫注入父類

[英]Injecting parent classes from other libraries with Guice

我正在嘗試使用Guice(4.0)從我的主驅動程序類中引導我的可執行文件的依賴項(也許這是Guice的反模式?):

// 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實際上擴展了MyApp在第三方(OSS)JAR中的基礎對象。 未設置此基類( Buzz )與Javax Inject或Guice一起使用。 但我希望Guice能夠配置其foobazwhistlefeather屬性...。

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

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

參見@Provides

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM