我想在不引入注释或使用字符串键名的情况下完成以下操作,是否可以使用Guice
?此外,引入第三个私有模块 forMyService
及其ExecutorService
绑定并不理想,因为我希望 ExecutorService 成为整个应用程序的单例,不仅注入到 中MyService
,还可能注入其他类,MyOtherService
例如。
public class Main {
public static void main(String[] args) {
final Injector injector = Guice.createInjector(new MyAppModule());
final MyService service = injector.getInstance(MyService.class);
service.printInternals();
// Ideally this would print something like:
// My Executor: ExecutorImplClass@1
// Red Executor: ExecutorImplClass@2
// Blue Executor: ExecutorImplClass@3
}
}
public class MyAppModule extends PrivateModule {
@Override
protected void configure() {
install(new RedModule());
install(new BlueModule());
bind(ExecutorService.class).toInstance(Executors.newSingleThreadExecutor());
bind(MyService.class).to(MyServiceImpl.class);
expose(MyService.class);
}
}
public class BlueModule extends PrivateModule {
@Override
protected void configure() {
bind(ExecutorService.class).toInstance(Executors.newSingleThreadExecutor());
bind(BlueService.class).to(BlueServiceImpl.class);
expose(BlueService.class);
}
}
public interface BlueService {
void printInternals();
}
class BlueServiceImpl implements BlueService {
private final ExecutorService executor;
@Inject
BlueServiceImpl(final ExecutorService executor) {
this.executor = executor;
}
@Override
public void printInternals() {
System.out.println("Blue Executor: " + executor);
}
}
RedModule, RedService and RedServiceImpl
所有镜像各自的Blue*
类。
最后MyService
,它使用Red
andBlue Services
以及它自己的ExecutorService
:
class MyServiceImpl implements MyService {
private final ExecutorService executor;
private final RedService red;
private final BlueService blue;
@Inject
MyServiceImpl(final ExecutorService executor, final RedService red, final BlueService blue) {
this.executor = executor;
this.red = red;
this.blue = blue;
}
@Override
public void printInternals() {
System.out.println("My Executor: " + executor);
red.printInternals();
blue.printInternals();
}
}