Configure PicoContainer with a factory method with

2019-07-25 18:29发布

I'd like to configure PicoContainer by giving it a factory method (as @Provides methods in Guice) to use to create a new instance every time I (re-)start the container. The main point here is that I need that instance to be a singleton during each cycle, in other words I want it to be cached.

1条回答
手持菜刀,她持情操
2楼-- · 2019-07-25 19:20

I found the solution: configuring a FactoryInjector

MutablePicoContainer pico = new PicoBuilder()
      .withCaching()
      .withLifecycle()
      .build();
pico.addAdapter(new FactoryInjector<WebDriver>(){
    @Override
    public WebDriver getComponentInstance(PicoContainer container, Type into) {
        return new FirefoxDriver();
    }
});
pico.start()
d1 = pico.getComponent(WebDriver.class);
d2 = pico.getComponent(WebDriver.class);
assert d1 == d2;
pico.stop();
pico.dispose();
d3 = pico.getComponent(WebDriver.class);
assert d1 != d3;

As you can see, pico will create a new instance only the first time. Any subsequent request before stopping the container will return the very same instance.

查看更多
登录 后发表回答