When using a DefaultPicoContainer with a given LifecycleStrategy (which includes a component monitor), the monitor is not automatically set for instances registered in the container. Cut and paste the code below in a file and run the (Junit 3) test:
/*
- expose the bug
*/
package some.package.name;
import java.lang.reflect.Constructor;
import junit.framework.TestCase;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.defaults.ComponentMonitorStrategy;
import org.picocontainer.defaults.DefaultPicoContainer;
import org.picocontainer.defaults.DelegatingComponentMonitor;
import org.picocontainer.defaults.MonitoringComponentAdapter;
import org.picocontainer.monitors.DefaultComponentMonitor;
public class DefaultPicoContainerTest extends TestCase {
public static class Instance {
// just a test
}
public static class LoggingComponentMonitor extends DefaultComponentMonitor {
private static int calls = 0;
@Override
public void instantiating(Constructor constructor) {
calls++;
}
static int getCalls() {
return calls;
}
}
public void testCorrectComponentMonitorRegisterImplementation() {
LoggingComponentMonitor monitor = new LoggingComponentMonitor();
DefaultPicoContainer container = new DefaultPicoContainer(monitor);
ComponentAdapter adapter = container.registerComponentImplementation(Instance.class);
assertSame(monitor, ((ComponentMonitorStrategy)adapter).currentMonitor());
}
public void testCorrectComponentMonitorRegisterInstance() {
LoggingComponentMonitor monitor = new LoggingComponentMonitor();
DefaultPicoContainer container = new DefaultPicoContainer(monitor);
ComponentAdapter adapter = container.registerComponentInstance(new Instance());
// direct call fails - this is a delegating component monitor
// assertSame(monitor, ((ComponentMonitorStrategy)adapter).currentMonitor());
int count = LoggingComponentMonitor.getCalls();
// however the failing test below proves that the LoggingComponentMonitor is not hit
((ComponentMonitorStrategy)adapter).currentMonitor().instantiating(null);
assertEquals(count + 1, LoggingComponentMonitor.getCalls());
}
}