@SuppressWarnings({"unchecked", "rawtypes" }) @Test public void circularScopedValue() throws Exception { RequestScope requestScope = new RequestScope(); Key<Object> key = Key.get(Object.class); try { new MockUnit(Provider.class, Map.class, CircularDependencyProxy.class) .expect(unit -> { Map scopedObjects = unit.get(Map.class); requestScope.enter(scopedObjects); expect(scopedObjects.get(key)).andReturn(null); expect(scopedObjects.containsKey(key)).andReturn(false); }) .expect(unit -> { Provider provider = unit.get(Provider.class); expect(provider.get()).andReturn(unit.get(CircularDependencyProxy.class)); }) .run(unit -> { Object result = requestScope.<Object> scope(key, unit.get(Provider.class)).get(); assertEquals(unit.get(CircularDependencyProxy.class), result); }); } finally { requestScope.exit(); } }
@Override public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { return () -> { if (scope == null) { throw new OutOfScopeException("Not in scope"); } Object value = scope.get(key); if (value == null) { T provided = unscoped.get(); if (provided instanceof CircularDependencyProxy) { return provided; } value = (provided == null) ? NULL_SENTINEL : provided; scope.put(key, value); } @SuppressWarnings("unchecked") T result = (value != NULL_SENTINEL) ? (T) value : null; return result; }; }
/** * Returns true if the object is a proxy for a circular dependency, constructed by Guice because * it encountered a circular dependency. Scope implementations should be careful to <b>not cache * circular proxies</b>, because the proxies are not intended for general purpose use. (They are * designed just to fulfill the immediate injection, not all injections. Caching them can lead to * IllegalArgumentExceptions or ClassCastExceptions.) * * @since 4.0 */ public static boolean isCircularProxy(Object object) { return object instanceof CircularDependencyProxy; }
/** * Returns true if the object is a proxy for a circular dependency, * constructed by Guice because it encountered a circular dependency. Scope * implementations should be careful to <b>not cache circular proxies</b>, * because the proxies are not intended for general purpose use. (They are * designed just to fulfill the immediate injection, not all injections. * Caching them can lead to IllegalArgumentExceptions or ClassCastExceptions.) */ public static boolean isCircularProxy(Object object) { return object instanceof CircularDependencyProxy; }