我正在尝试使用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
实际上扩展了第三方(OSS)JAR中的基础对象。此基类(Buzz
)未设置为与Javax Inject或Guice一起使用。但我希望Guice能够配置其foobaz
和whistlefeather
属性....任何想法?
答案 0 :(得分:1)
您可以在Guice模块中使用@Provide
方法创建和注入任何bean。例如:
@Provides
MyApp externalService(DatabaseClient dbClient, Whistlefeather wf) {
MyApp app = new MyApp();
app.setDatabaseCLient(dbClient);
app.setWhitlefeature(wf);
return app;
}
请参阅@Provides