Created
December 23, 2011 23:46
-
-
Save aolshevskiy/1515705 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import com.google.inject.*; | |
import com.google.inject.name.Named; | |
import com.google.inject.name.Names; | |
import com.google.inject.servlet.SessionScoped; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.concurrent.Callable; | |
/** | |
* Created by IntelliJ IDEA. | |
* User: siasia | |
* Date: 22.12.11 | |
* Time: 0:44 | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class Test { | |
public static void main(String args[]) { | |
Injector injector = Guice.createInjector(new TestModule()); | |
TestOne one = injector.getInstance(TestOne.class); | |
one.run(); | |
} | |
} | |
class TestOne { | |
private final TestTwo two; | |
private final SimpleScope session; | |
@Inject | |
TestOne(TestTwo two, @Named("sessionScope") SimpleScope session) { | |
this.two = two; | |
this.session = session; | |
} | |
void run() { | |
for(int i = 0; i<3; i++) | |
session.inScope(new Runnable() { | |
@Override | |
public void run() { | |
for(int i = 0; i < 3; i++) | |
two.run(); | |
} | |
}); | |
} | |
} | |
class TestTwo { | |
private final Provider<SessScoped> scoped; | |
@Inject | |
TestTwo(Provider<SessScoped> scoped) { | |
this.scoped = scoped; | |
} | |
void run() { | |
System.out.println(scoped.get()); | |
} | |
} | |
class SimpleScope implements Scope { | |
Map<Key<?>, Object> values = null; | |
void inScope(Runnable code) { | |
if(values != null) | |
throw new IllegalStateException("Session already in progress"); | |
values = new HashMap<Key<?>, Object>(); | |
code.run(); | |
if(values == null) | |
throw new IllegalStateException("No session in progress"); | |
values = null; | |
} | |
@Override | |
public <T> Provider<T> scope(final Key<T> tKey, final Provider<T> provider) { | |
return new Provider<T>() { | |
@Override | |
public T get() { | |
if(!values.containsKey(tKey)) | |
values.put(tKey, provider.get()); | |
return (T)values.get(tKey); | |
} | |
}; | |
} | |
@Override | |
public String toString() { | |
return "SESSION"; | |
} | |
} | |
class SessScoped { | |
} | |
class TestModule extends AbstractModule { | |
@Override | |
protected void configure() { | |
SimpleScope session = new SimpleScope(); | |
bindScope(SessionScoped.class, session); | |
bind(SimpleScope.class).annotatedWith(Names.named("sessionScope")).toInstance(session); | |
bind(SessScoped.class).in(SessionScoped.class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment