Skip to content

Instantly share code, notes, and snippets.

@mhaligowski
Created March 12, 2017 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhaligowski/057e2e2a4949063b8d8e347086dfb6d2 to your computer and use it in GitHub Desktop.
Save mhaligowski/057e2e2a4949063b8d8e347086dfb6d2 to your computer and use it in GitHub Desktop.
Super simple Scope in Guice
import com.google.inject.*;
import javax.inject.Inject;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@ScopeAnnotation
@Retention(RUNTIME)
@interface NameScoped {
}
public class ScopesModule extends AbstractModule {
@Override
protected void configure() {
NameScope scope = new NameScope();
bindScope(NameScoped.class, scope);
bind(String.class).in(NameScoped.class);
bind(Greeter.class);
}
}
class Greeter {
@Inject
private String name;
String greet() {
return "Hello, " + name;
}
}
class NameProvider implements Provider<String> {
private final String name;
NameProvider(final String name) {
this.name = name;
}
@Override
public String get() {
return this.name;
}
}
class NameScope implements Scope {
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
return (Provider<T>) new NameProvider("Joe");
}
}
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ScopesModuleTest {
@Test
public void should_return_object_with_scoped_value() {
// given
final ScopesModule scopesModule = new ScopesModule();
final Injector injector = Guice.createInjector(scopesModule);
final Greeter instance = injector.getInstance(Greeter.class);
assertThat(instance).isNotNull();
final String greet = instance.greet();
assertThat(greet).isEqualTo("Hello, Joe");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment