T. *_*ayo 4 java dependency-injection guice
我正在使用guice在我的构造函数中动态注入类.例如:
@Inject
public PublisherFrame(EventBus eventBus, MyPublisherService publishService)
Run Code Online (Sandbox Code Playgroud)
在我的guice模块中:
bind(EventBus.class).in(Singleton.class);
bind(MyPublisherService.class).in(Singleton.class);
Run Code Online (Sandbox Code Playgroud)
工作没有问题.
当我创建一个具有在java代码中构造的参数的对象时,问题就开始了:
public LoginController(EventBus eventBus, MyPublisherService publisherService, LoginDialog dlg)
Run Code Online (Sandbox Code Playgroud)
这里的LoginDialog是java代码创建的java类.为了解决这个问题,我使用了@assist和:
install(new FactoryModuleBuilder().implement(ILoginController.class, LoginController.class).build(GuiceLoginControllerFactory.class));
Run Code Online (Sandbox Code Playgroud)
工作也很好.但现在我必须创建2个额外的java文件:
有没有更简单的方法来注入一个在构造函数中有自定义参数的变量?(没有创建2个额外的"guice"帮助文件)
Jef*_*ica 10
您实际上并不需要类本身的附加接口(参见下文).此外,我通常将我的工厂创建为它创建的类的嵌套接口:
public class LoginController {
public interface Factory {
LoginController create(LoginDialog dlg);
}
@Inject public LoginController(
EventBus eventBus,
MyPublisherService publisherService,
@Assisted LoginDialog dlg) { /* ... */ }
}
// in your module
install(new FactoryModuleBuilder().build(LoginController.Factory.class));
Run Code Online (Sandbox Code Playgroud)
FactoryModuleBuilder.implement除非您希望Factory的工厂方法的返回类型是接口而不是具体类,否则不需要调用- 然后Guice将不知道在没有您的帮助的情况下构造什么类型的具体类型.在下面的示例中,您无法要求FactoryModuleBuilder LoginService.Factory为您实现,因为它不知道要实例化哪个具体的LoginService实现者:
interface LoginService {
interface Factory {
LoginService create(NetConnection connection);
}
boolean login(String username, String password);
}
class SimpleLoginService implements LoginService {
@Inject SimpleLoginService(@Assisted NetConnection connection) { /* ... */ }
}
class SecuredLoginService implements LoginService {
@Inject SecuredLoginService(
EncryptionService encryptionService,
@Assisted NetConnection connection) { /* ... */ }
}
// in your module: implements LoginService.Factory
install(new FactoryModuleBuilder()
.implement(LoginService.class, SimpleLoginService.class)
.build(LoginService.Factory.class));
// this one implements @Secured LoginService.Factory
install(new FactoryModuleBuilder()
.implement(LoginService.class, SecuredLoginService.class)
.build(Key.get(LoginService.Factory.class, Secured.class));
Run Code Online (Sandbox Code Playgroud)
除此之外,condit创建setter方法的想法并不坏,但这确实意味着你正在以部分初始化状态构建你的类.