使 Guice 注入器为单例以保证一致性
我想知道注射器通常是如何使用的。我知道它主要在启动时使用,但是如何在运行时使用它来创建特定实现的对象?
例如,我有一个 User 接口,其中实现了 UserA、UserB 和 UserC。我在运行时使用 Guice 的想法是将其包装在 Singleton 类中,以便我可以检索它,而不是每次我想创建 User 对象的实例时创建一个新的注入器。
//Create in singleton wrapper class
Injector injector = Guice.createInjector(new SecurityModule());
//Retrieve and use at run-time (Manager is the singleton wrapper class)
Injector injector = Manager.getInstance().getInjector();
User user = injector.getInstance(User.class);
这是通常的做法吗?基本上,我想确保集中所有配置,以便减少错误(例如使用错误的模块)。它也更容易管理,因此如果我决定使用不同的配置模块,我可以在一个类中更改它,而不是在每个使用它的 Java 类中更改它。
谢谢, 杰克
I was wondering how the injector is typically used. I understand that it's used mainly at start-up time, but how would you use it at run-time to create an object of certain implementation?
For example, I have an interface User with implementation of UserA, UserB and UserC. My idea of using Guice at run-time is to wrap it in a Singleton class so that I can get retrieve it rather than creating a new injector every time I want to create an instance of User object.
//Create in singleton wrapper class
Injector injector = Guice.createInjector(new SecurityModule());
//Retrieve and use at run-time (Manager is the singleton wrapper class)
Injector injector = Manager.getInstance().getInjector();
User user = injector.getInstance(User.class);
Is this how it's typically done? Basically, I want to make sure that I centralize all configuration so that there is less error (e.g. using the wrong module). It's also easier to manage so if I decided to use a different configuration module, I can just change it in a class, rather than in every Java class that is using it.
Thanks,
Jack
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非在极少数和特定的情况下,否则您不需要直接在应用程序中使用
Injector
,即使这样,您也绝对不应该将其设为静态单例。如果您希望能够在应用程序中的某个位置使用 Guice 检索User
的新实例,您应该只注入Provider
并调用get()
当你需要的时候就可以了。You shouldn't need to use the
Injector
directly in an application except in rare and specific circumstances, and even then you definitely should not make it a static Singleton. If you want to be able to retrieve new instances ofUser
using Guice somewhere in your application, you should just inject aProvider<User>
and callget()
on it when you need.我会写:
这样你就可以执行
Manager.getInstance().get(User.class) ,而不必使用 Guice 的注入器,从而允许你更改依赖注入框架而不更改应用程序代码。
I would write:
so you can do
Manager.getInstance().get(User.class)
and not have to use the Injector from Guice, allowing you to change Dependency Injection framework without changing your application code.