使用 Guice 从其他库注入父 类

Injecting parent classes from other libraries with Guice

我正在尝试使用 Guice (4.0) 到 bootstrap 从我的主驱动程序内部对我的可执行文件的依赖项 class(也许这是一个 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 实际上扩展了第 3 方 (OSS) JAR 中的基础对象。此基础 class (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