Last active
July 19, 2017 20:19
-
-
Save electrum/8cb4183e29008efb0f37b34dc2ceb0e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package javatest8; | |
import com.google.inject.Binder; | |
import com.google.inject.Guice; | |
import com.google.inject.Injector; | |
import com.google.inject.Key; | |
import com.google.inject.Module; | |
import com.google.inject.matcher.Matchers; | |
import com.google.inject.spi.Dependency; | |
import com.google.inject.spi.DependencyAndSource; | |
import com.google.inject.spi.ProvisionListener; | |
import io.airlift.log.Logger; | |
import javax.inject.Inject; | |
import javax.inject.Provider; | |
public final class GuiceLogger | |
{ | |
public static void main(String[] args) | |
{ | |
Injector injector = Guice.createInjector(new LoggerModule()); | |
injector.getInstance(Foo.class); | |
injector.getInstance(Bar.class); | |
} | |
public static class Foo | |
{ | |
@Inject | |
public Foo(java.util.logging.Logger logger) | |
{ | |
logger.warning("foo"); | |
} | |
} | |
public static class Bar | |
{ | |
@Inject | |
public Bar(Logger logger) | |
{ | |
logger.warn("bar"); | |
} | |
} | |
private static class LoggerModule | |
implements Module | |
{ | |
@Override | |
public void configure(Binder binder) | |
{ | |
ThreadLocal<Class<?>> target = new ThreadLocal<>(); | |
binder.bind(Logger.class).toProvider((Provider<Logger>) () -> | |
(target.get() != null) ? Logger.get(target.get()) : Logger.get("")); | |
binder.bindListener(Matchers.any(), new ProvisionListener() | |
{ | |
@Override | |
public <T> void onProvision(ProvisionInvocation<T> provision) | |
{ | |
for (DependencyAndSource entry : provision.getDependencyChain()) { | |
Dependency<?> dependency = entry.getDependency(); | |
if (dependency != null && dependency.getKey().equals(Key.get(Logger.class))) { | |
target.set(dependency.getInjectionPoint().getMember().getDeclaringClass()); | |
try { | |
provision.provision(); | |
} | |
finally { | |
target.remove(); | |
} | |
} | |
} | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment