Skip to content

Instantly share code, notes, and snippets.

@electrotype
Created August 21, 2013 15:57
Show Gist options
  • Save electrotype/6296350 to your computer and use it in GitHub Desktop.
Save electrotype/6296350 to your computer and use it in GitHub Desktop.
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.spi.ProvisionListener;
public class TestBindListener
{
public static interface IInitableAfterCreation
{
void init();
}
public static interface IClassAAA
{
boolean isInited();
}
public static class ClassAAA implements IClassAAA, IInitableAfterCreation
{
boolean inited = false;
@Override
public boolean isInited()
{
return this.inited;
}
@Override
public void init()
{
this.inited = true;
}
}
public static interface IClassAAAFactory
{
public IClassAAA create();
}
@Test
public void testBindListenerNoAssistedFactory()
{
Injector injector = Guice.createInjector(new AbstractModule()
{
@Override
protected void configure()
{
bind(IClassAAA.class).to(ClassAAA.class);
bindListener(new AbstractMatcher<Binding<?>>()
{
@Override
public boolean matches(Binding<?> t)
{
return IInitableAfterCreation.class.isAssignableFrom(t.getKey().getTypeLiteral().getRawType());
}
},
new ProvisionListener()
{
@Override
public <T> void onProvision(ProvisionInvocation<T> provision)
{
Object obj = provision.provision();
if(obj instanceof IInitableAfterCreation)
{
((IInitableAfterCreation)obj).init();
}
}
});
}
});
IClassAAA classAAA = injector.getInstance(IClassAAA.class);
assertNotNull(classAAA);
assertTrue(classAAA.isInited());
}
@Test
public void testBindListenerWithAssistedFactory()
{
Injector injector = Guice.createInjector(new AbstractModule()
{
@Override
protected void configure()
{
install(new FactoryModuleBuilder().implement(IClassAAA.class, ClassAAA.class)
.build(IClassAAAFactory.class));
bindListener(new AbstractMatcher<Binding<?>>()
{
@Override
public boolean matches(Binding<?> t)
{
return IInitableAfterCreation.class.isAssignableFrom(t.getKey().getTypeLiteral().getRawType());
}
},
new ProvisionListener()
{
@Override
public <T> void onProvision(ProvisionInvocation<T> provision)
{
Object obj = provision.provision();
if(obj instanceof IInitableAfterCreation)
{
((IInitableAfterCreation)obj).init();
}
}
});
}
});
IClassAAAFactory classAAAFactory = injector.getInstance(IClassAAAFactory.class);
assertNotNull(classAAAFactory);
IClassAAA classAAA = classAAAFactory.create();
assertNotNull(classAAA);
assertTrue(classAAA.isInited());
}
}
@electrotype
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment