问题
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