简体   繁体   中英

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. Is there any other robo-solution ?

This use case is impossible to implements using 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
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM