简体   繁体   English

Roboguice-一个接口的两种实现

[英]Roboguice - Two implementations for one interface

My code is like this: 我的代码是这样的:

interface MyIntreface{
     ...
}

class A implements MyInterface{}     
class B implements MyInterface{}  

class BaseClass{
    @Inject
    MyInterface  instance;
}

class MyFirstClass extends BaseClass{
   ....
}

class MySecondClass extends BaseClass{
   ....
}

Now I want to MyFirstClass have implementation A and MySecondClass implementation B. @Named annotations seems not to work in this case. 现在,我要MyFirstClass具有实现A和MySecondClass实现B。@Named注释在这种情况下似乎不起作用。 Is there any other robo-solution ? 还有其他机器人解决方案吗?

This use case is impossible to implements using Roboguice. 使用Roboguice不可能实现该用例。 But there are two ways to resolve your problem. 但是有两种方法可以解决您的问题。

  • Implement provider that injects MyFirstClass and MySecondClass and then inject to provider A or B and use setter to set it in created instance 实现提供程序,该提供程序注入MyFirstClass和MySecondClass,然后注入到提供程序A或B,并使用setter在创建的实例中对其进行设置
  • class Baclass BaseClass{ protected abstract MyInterface extractMyInterface();
    } class MyFirstClass extends BaseClass{ @Inject B instance; protected MyInterface extractMyInterface() { return instance; }
    } class MySecondClass extends BaseClass{ @Inject A instance; protected MyInterface extractMyInterface() { return instance; } }

In my opinion the first one (with Provider) is much more cleaner. 我认为第一个(与提供程序一起使用)更清洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 与两种不同实现的接口 - Interface with two different implementations 使用@PROFILE管理一个Spring接口的两个或多个实现 - managing two or more implementations of one Spring interface With @PROFILE 如果没有可用的公共接口,则使用一个类的两种实现的模式 - Pattern for using two implementations of one class if no common interface available Jersey/HK2 中一个接口的两个实现,首先在另一个中重用 - Two implementations of one interface in Jersey/HK2, reuse first in other 具有不同类型的接口的两种实现 - 这不可能吗? - Two implementations for an interface with different types - Is this not possible? 在接口的两个实现之间移动公共代码 - Moving common code between two implementations of interface 处理一个Spring bean /接口的几个实现 - Handling several implementations of one Spring bean/interface Maven项目组织:一个接口多个实现 - Maven project organization: one interface multiple implementations 在一个类字段中处理一个Spring bean /接口的几个实现 - Handling several implementations of one Spring bean/interface in one class field 一种接口实现多种实现。 如何在运行时获得合适的 - One interface multipe implementations. How get the right one at runtime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM