Configure PicoContainer with a factory method with caching behavior

坚强是说给别人听的谎言 提交于 2019-12-24 07:30:00

问题


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:


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.



来源:https://stackoverflow.com/questions/44543494/configure-picocontainer-with-a-factory-method-with-caching-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!