1 16 17 package com.google.inject; 18 19 import com.google.inject.util.StackTraceElements; 20 import java.lang.annotation.Annotation ; 21 import java.util.Map ; 22 23 28 public class Scopes { 29 30 private Scopes() {} 31 32 35 public static final Scope SINGLETON = new Scope() { 36 public <T> Provider<T> scope(Key<T> key, final Provider<T> creator) { 37 return new Provider<T>() { 38 39 private volatile T instance; 40 41 @SuppressWarnings ("DoubleCheckedLocking") 43 public T get() { 44 if (instance == null) { 45 51 synchronized (Injector.class) { 52 if (instance == null) { 53 instance = creator.get(); 54 } 55 } 56 } 57 return instance; 58 } 59 60 public String toString() { 61 return creator.toString(); 62 } 63 }; 64 } 65 66 public String toString() { 67 return "Scopes.SINGLETON"; 68 } 69 }; 70 71 79 static Scope getScopeForType(Class <?> implementation, 80 Map <Class <? extends Annotation >, Scope> scopes, 81 ErrorHandler errorHandler) { 82 Class <? extends Annotation > found = null; 83 for (Annotation annotation : implementation.getAnnotations()) { 84 if (isScopeAnnotation(annotation)) { 85 if (found != null) { 86 errorHandler.handle( 87 StackTraceElements.forType(implementation), 88 ErrorMessages.DUPLICATE_SCOPE_ANNOTATIONS, 89 "@" + found.getSimpleName(), 90 "@" + annotation.annotationType().getSimpleName() 91 ); 92 } else { 93 found = annotation.annotationType(); 94 } 95 } 96 } 97 98 return scopes.get(found); 99 } 100 101 static boolean isScopeAnnotation(Annotation annotation) { 102 return isScopeAnnotation(annotation.annotationType()); 103 } 104 105 static boolean isScopeAnnotation(Class <? extends Annotation > annotationType) { 106 return annotationType.isAnnotationPresent(ScopeAnnotation.class); 107 } 108 109 112 static <T> InternalFactory<? extends T> scope(Key<T> key, 113 InjectorImpl injector, InternalFactory<? extends T> creator, 114 Scope scope) { 115 if (scope == null) { 117 return creator; 118 } 119 Provider<T> scoped = scope.scope(key, 120 new ProviderToInternalFactoryAdapter<T>(injector, creator)); 121 return new InternalFactoryToProviderAdapter<T>(scoped); 122 } 123 } 124 | Popular Tags |