struts2源碼分析(依賴注入)

1、首先Inject(com.opensymphony.xwork2.inject)這個Annotation類

這個類是對Inject的定義,其內容如下:

/**
 * @Retention(RetentionPolicy.RUNTIME)在這裏指定了註解保留的週期;有三個週期
 * CLASS:編譯器將把註釋記錄在類文件中,但在運行時 VM 不需要保留註釋。
 * RUNTIME:編譯器將把註釋記錄在類文件中,在運行時 VM 將保留註釋,因此可以反射性地讀取。
 * SOURCE:編譯器要丟棄的註釋。
 * @Target(ElementType.TYPE)  這個標識註解應該標在那裏   ElementType的幾個枚舉值就代表了  註解應該寫在的位置
 * CONSTRUCTOR:構造方法聲明
 * FIELD:字段聲明(包括枚舉常量)
 * LOCAL_VARIABLE: 局部變量聲明
 * METHOD:方法聲明
 * PACKAGE:包聲明
 * PARAMETER:參數聲明
 * TYPE: 類、接口(包括註釋類型)或枚舉聲明
 */
@Target({METHOD, CONSTRUCTOR, FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface Inject {

  /**
   * 依賴的名字. 默認爲Struts2的Container中的DEFAULT_NAME(default).
   */
  String value() default DEFAULT_NAME;

  /**
   * 是否必須注入. 
   */
  boolean required() default true;
}

2、Struts2內部的依賴注入核心參考《Struts2的IoC解析

鏈接地址爲:http://blog.csdn.net/yanlinwang/article/details/8944632

3、以下是對Struts2的個人理解

/**
 * 默認Container的實現
 */
@SuppressWarnings("serial")
class ContainerImpl implements Container {

	/**
	 * bean容器
	 */
	final Map<Key<?>, InternalFactory<?>> factories;
	/**
	 * 定義一個類型到名稱集合的映射關係,一個類型對應於多個名稱 
	 */
	final Map<Class<?>, Set<String>> factoryNamesByType;

	/**
	 * 構造方法、在該方法中對factories和factoryNamesByType進行初始化
	 * @param factories
	 */
	ContainerImpl( Map<Key<?>, InternalFactory<?>> factories ) {
		//初始化factories
		this.factories = factories;
		//一個類型對應於多個名稱,構建一個類型到名稱集合的映射關係
		Map<Class<?>, Set<String>> map = new HashMap<Class<?>, Set<String>>();
		
		/**
		 * 對factories進行遍歷
		 */
		for ( Key<?> key : factories.keySet() ) {
			Set<String> names = map.get(key.getType());
			if (names == null) {
				names = new HashSet<String>();
				map.put(key.getType(), names);
			}
			names.add(key.getName());
		}
		/**
		 * 將名稱集合固化爲不可修改的
		 */
		for ( Entry<Class<?>, Set<String>> entry : map.entrySet() ) {
			entry.setValue(Collections.unmodifiableSet(entry.getValue()));
		}
		//將類型到名稱集合的映射關係固化爲不可修改
		this.factoryNamesByType = Collections.unmodifiableMap(map);
	}

	/**
	 * 根據KEY找到該類型的構造工廠類 
	 * @param <T>
	 * @param key 類型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	<T> InternalFactory<? extends T> getFactory( Key<T> key ) {
		return (InternalFactory<T>) factories.get(key);
	}

	/**
	 * 初始化一個注入器map,用來保存類和其注入器之間的關係
	 * 該變量是ReferenceCache的一個實例
	 */
	final Map<Class<?>, List<Injector>> injectors = new ReferenceCache<Class<?>, List<Injector>>() {
				@Override
				protected List<Injector> create( Class<?> key ) {
					List<Injector> injectors = new ArrayList<Injector>();
					addInjectors(key, injectors);//在這裏對key進行依賴注入
					return injectors;
				}
			};

	/**
	 * 從給定的類中循環向給定的列表中注入變量和方法。父類在子類之前注入
	 */
	void addInjectors( Class clazz, List<Injector> injectors ) {
		if (clazz == Object.class) {
			return;
		}

		//向父類進行遞歸,爲其父類進行依賴注入,直到遇到Object類爲止
		addInjectors(clazz.getSuperclass(), injectors);

		// TODO (crazybob): Filter out overridden members.
		/**
		 * 通過該方法,將需要注入的非靜態屬性放入injectors中
		 */
		addInjectorsForFields(clazz.getDeclaredFields(), false, injectors);
		/**
		 * 通過該方法,將需要注入的非靜態方法放入injectors中
		 */
		addInjectorsForMethods(clazz.getDeclaredMethods(), false, injectors);
	}

	/**
	 * 依賴注入(靜態參數、方法)
	 * @param staticInjections
	 */
	void injectStatics( List<Class<?>> staticInjections ) {
		final List<Injector> injectors = new ArrayList<Injector>();

		/**
		 * 對參數staticInjections進行遍歷
		 */
		for ( Class<?> clazz : staticInjections ) {
			//class的getDeclaredFields()方法返回此 Class 對象所表示的類或接口所聲明的所有字段
			/**
			 * 通過該方法,將需要注入的靜態屬性放入injectors中
			 */
			addInjectorsForFields(clazz.getDeclaredFields(), true, injectors);
			//class的getDeclaredMethods()方法返回此 Class 對象表示的類或接口聲明的所有方法,包括公共、保護、默認(包)訪問和私有方法,但不包括繼承的方法。
			/**
			 * 通過該方法,將需要注入的靜態方法放入injectors中
			 */
			addInjectorsForMethods(clazz.getDeclaredMethods(), true, injectors);
		}

		callInContext(new ContextualCallable<Void>() {
			/**
			 * 實現該ContextualCallable接口中的call方法
			 */
			public Void call( InternalContext context ) {
				for ( Injector injector : injectors ) {
					injector.inject(context, null);
				}
				return null;
			}
		});
	}
	
	/**
	 * 找到對象所定義的全部方法,並且表示成注入器列表方式
	 * @param methods
	 * @param statics
	 * @param injectors
	 */
	void addInjectorsForMethods( Method[] methods, boolean statics, List<Injector> injectors ) {
		addInjectorsForMembers(Arrays.asList(methods), statics, injectors,
				new InjectorFactory<Method>() {
					public Injector create( ContainerImpl container, Method method,
											String name ) throws MissingDependencyException {
						return new MethodInjector(container, method, name);
					}
				});
	}

	/**
	 * 找到對象所定義的全部字段,並且表示成注入器列表方式 
	 * @param fields 某個類的所有屬性
	 * @param statics false
	 * @param injectors 
	 */
	void addInjectorsForFields( Field[] fields, boolean statics, List<Injector> injectors ) {
		//Arrays.asList();返回一個受指定數組支持的固定大小的列表
		addInjectorsForMembers(Arrays.asList(fields), statics, injectors,
				new InjectorFactory<Field>() {
					public Injector create( ContainerImpl container, Field field, String name ) throws MissingDependencyException {
						return new FieldInjector(container, field, name);
					}
				});
	}
	
	/**
	 * 找到有註解@Inject的成員,調用傳入的injectorFactory.create方法創建真正的Injector實例 加入到注入器集合中 
	 * @param <M>
	 * @param members 參數或是方法列表
	 * @param statics 
	 * @param injectors a new Object
	 * @param injectorFactory
	 */
	<M extends Member & AnnotatedElement> void addInjectorsForMembers(List<M> members, boolean statics, List<Injector> injectors, InjectorFactory<M> injectorFactory ) {
		//對members對象進行遍歷
		for ( M member : members ) {
			if (isStatic(member) == statics) {
				//如果存在該元素的指定類型的註釋,則返回這些註釋,否則返回 null。
				Inject inject = member.getAnnotation(Inject.class);
				//這裏inject.value()默認爲default
				if (inject != null) {
					try {
						injectors.add(injectorFactory.create(this, member, inject.value()));//把這個Member放入injectors中
					} catch ( MissingDependencyException e ) {
						if (inject.required()) {
							throw new DependencyException(e);
						}
					}
				}
			}
		}
	}

	/**
	 * 注入器工廠接口
	 * @author Administrator
	 *
	 * @param <M>
	 */
	interface InjectorFactory<M extends Member & AnnotatedElement> {

		Injector create( ContainerImpl container, M member, String name ) throws MissingDependencyException;
	}

	/**
	 * 檢查成員是否爲靜態的
	 * @param member
	 * @return
	 */
	private boolean isStatic( Member member ) {
		//member.getModifiers()返回作爲整數返回由此 Member 所表示的成員或構造方法的 Java 語言修飾符
		//Modifier.isStatic()如果整數參數包括 static 修飾符,則返回 true,否則返回 false。
		return Modifier.isStatic(member.getModifiers());
	}

	/**
	 * 字段屬性注入器
	 * @author Administrator
	 *
	 */
	static class FieldInjector implements Injector {

		final Field field;
		//類加載的時候需要注入的成員
		final InternalFactory<?> factory;
		//運行時需要注入的成員
		final ExternalContext<?> externalContext;

		/**
		 * 屬性注入構造器
		 * @param container 容器實例
		 * @param field 字段
		 * @param name 屬性字段名稱
		 * @throws MissingDependencyException
		 */
		public FieldInjector( ContainerImpl container, Field field, String name )throws MissingDependencyException {
			this.field = field;//初始化field字段
			//field.isAccessible獲取此對象的 accessible 標誌的值。
			if (!field.isAccessible()) {
				SecurityManager sm = System.getSecurityManager();
				try {
					if (sm != null) {
						//如果基於當前有效的安全策略,不允許執行根據給定權限所指定的請求訪問,則拋出 SecurityException。
						//反射操作的 Permission 類。ReflectPermission 是一種指定權限,沒有動作
						sm.checkPermission(new ReflectPermission("suppressAccessChecks"));
					}
					//設定該字段的accessible
					field.setAccessible(true);
				} catch ( AccessControlException e ) {
					throw new DependencyException("Security manager in use, could not access field: "
							+ field.getDeclaringClass().getName() + "(" + field.getName() + ")", e);
				}
			}
			//創建一個基於field的key的實例
			Key<?> key = Key.newInstance(field.getType(), name);
			//從當前的factory中獲取該key的工廠類
			factory = container.getFactory(key);
			//如果不存在則拋出異常
			if (factory == null) {
				throw new MissingDependencyException(
						"No mapping found for dependency " + key + " in " + field + ".");
			}
			//實例化一個externalContext
			this.externalContext = ExternalContext.newInstance(field, key, container);
		}

		/**
		 * 將傳入的對象的字段設置值
		 * @param context 內部上下文
		 * @param o 傳入對象
		 */
		public void inject( InternalContext context, Object o ) {
			ExternalContext<?> previous = context.getExternalContext();
			context.setExternalContext(externalContext);
			try {
				field.set(o, factory.create(context));//對field進行賦值
			} catch ( IllegalAccessException e ) {
				throw new AssertionError(e);
			} finally {
				context.setExternalContext(previous);
			}
		}
	}

	/**
	 * 獲取參數的injectors
	 *
	 * @param member		 參數所屬的Member
	 * @param annotations	參數上面的Annotation
	 * @param parameterTypes 參數類型
	 *
	 * @return injections
	 */
	<M extends AccessibleObject & Member> ParameterInjector<?>[]
	getParametersInjectors( M member, Annotation[][] annotations, Class[] parameterTypes, String defaultName ) throws MissingDependencyException {
		List<ParameterInjector<?>> parameterInjectors = new ArrayList<ParameterInjector<?>>();//創建一個新的ParameterInjector集合
		Iterator<Annotation[]> annotationsIterator = Arrays.asList(annotations).iterator();//把annotations參數轉換成Iterator對象
		/**
		 * 對Iterator對象進行遍歷
		 */
		for ( Class<?> parameterType : parameterTypes ) {
			Inject annotation = findInject(annotationsIterator.next());//獲取annotations參數中的Inject註解的Annotation
			String name = annotation == null ? defaultName : annotation.value();//獲取annotation的value
			Key<?> key = Key.newInstance(parameterType, name);//將其組裝成一個KEY
			parameterInjectors.add(createParameterInjector(key, member));
		}

		return toArray(parameterInjectors);
	}

	/**
	 * 根據KEY從factories中獲取該key的工廠類
	 * @param <T>
	 * @param key
	 * @param member
	 * @return
	 * @throws MissingDependencyException
	 */
	<T> ParameterInjector<T> createParameterInjector( Key<T> key, Member member ) throws MissingDependencyException {
		InternalFactory<? extends T> factory = getFactory(key);//獲取指定key的工廠類
		/**
		 * 如果此工廠類不存在,則拋出異常
		 */
		if (factory == null) {
			throw new MissingDependencyException("No mapping found for dependency " + key + " in " + member + ".");
		}
		
		ExternalContext<T> externalContext = ExternalContext.newInstance(member, key, this);
		return new ParameterInjector<T>(externalContext, factory);//返回一個新的ParameterInjector對象
	}

	/**
	 * 把parameterInjector的集合轉換成一個ParameterInjector的數組
	 * @param parameterInjections
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private ParameterInjector<?>[] toArray(List<ParameterInjector<?>> parameterInjections ) {
		return parameterInjections.toArray(new ParameterInjector[parameterInjections.size()]);
	}

	/**
	 * 獲取annotations參數中的Inject註解的Annotation
	 */
	Inject findInject( Annotation[] annotations ) {
		for ( Annotation annotation : annotations ) {
			if (annotation.annotationType() == Inject.class) {
				return Inject.class.cast(annotation);
			}
		}
		return null;
	}

	/**
	 * 方法注入器定義,負責以對象方法方式注入對象 
	 * @author Administrator
	 *
	 */
	static class MethodInjector implements Injector {

		/**
		 * 方法
		 */
		final Method method;
		/**
		 * 參數注入器
		 */
		final ParameterInjector<?>[] parameterInjectors;

		/**
		 * 默認構造方法,在該方法中初始化參數
		 * @param container
		 * @param method
		 * @param name
		 * @throws MissingDependencyException
		 */
		public MethodInjector( ContainerImpl container, Method method, String name ) throws MissingDependencyException {
			//初始化method
			this.method = method;
			/**
			 * 對method進行包裝
			 */
			if (!method.isAccessible()) {
				SecurityManager sm = System.getSecurityManager();
				try {
					if (sm != null) {
						sm.checkPermission(new ReflectPermission("suppressAccessChecks"));
					}
					method.setAccessible(true);
				} catch ( AccessControlException e ) {
					throw new DependencyException("Security manager in use, could not access method: "
							+ name + "(" + method.getName() + ")", e);
				}
			}
			//按照聲明順序返回 Class 對象的數組,這些對象描述了此 Method 對象所表示的方法的形參類型。
			Class<?>[] parameterTypes = method.getParameterTypes();
			//如果此Method的所有的方法的形參類型爲0,則拋出異常
			if (parameterTypes.length == 0) {
				throw new DependencyException(method + " has no parameters to inject.");
			}
			/**
			 * 獲取形參的injector,該對象是ParameterInjector類型的數組
			 */
			parameterInjectors = container.getParametersInjectors(method, method.getParameterAnnotations(), parameterTypes, name);
		}

		/**
		 * 採用反射機制對方法進行注入
		 */
		public void inject( InternalContext context, Object o ) {
			try {
				/**
				 * 進行方法的依賴注入
				 */
				method.invoke(o, getParameters(method, context, parameterInjectors));
			} catch ( Exception e ) {
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 構造方法的注入
	 */
	Map<Class<?>, ConstructorInjector> constructors = new ReferenceCache<Class<?>, ConstructorInjector>() {
				@Override
				@SuppressWarnings("unchecked")
				protected ConstructorInjector<?> create( Class<?> implementation ) {
					return new ConstructorInjector(ContainerImpl.this, implementation);
				}
			};

	/**
	 * 構造函數注入器
	 * @author Administrator
	 *
	 * @param <T>
	 */
	static class ConstructorInjector<T> {

		/**
		 * 要處理的類型
		 */
		final Class<T> implementation;
		/**
		 * 需要注入的屬性或者方法
		 */
		final List<Injector> injectors;
		/**
		 * 構造器
		 */
		final Constructor<T> constructor;
		/**
		 * 需要注入的參數數組
		 */
		final ParameterInjector<?>[] parameterInjectors;

		/**
		 * 構造方法,在該方法中初始化implementation
		 * @param container
		 * @param implementation
		 */
		ConstructorInjector( ContainerImpl container, Class<T> implementation ) {
			//初始化implementation
			this.implementation = implementation;

			constructor = findConstructorIn(implementation);
			if (!constructor.isAccessible()) {
				SecurityManager sm = System.getSecurityManager();
				try {
					if (sm != null) {
						sm.checkPermission(new ReflectPermission("suppressAccessChecks"));
					}
					constructor.setAccessible(true);
				} catch ( AccessControlException e ) {
					throw new DependencyException("Security manager in use, could not access constructor: "
							+ implementation.getName() + "(" + constructor.getName() + ")", e);
				}
			}

			MissingDependencyException exception = null;
			Inject inject = null;
			ParameterInjector<?>[] parameters = null;

			try {
				//取得註解方式聲明的注入依賴
				inject = constructor.getAnnotation(Inject.class);
				parameters = constructParameterInjector(inject, container, constructor);
			} catch ( MissingDependencyException e ) {
				exception = e;
			}
			parameterInjectors = parameters;

			if (exception != null) {
				if (inject != null && inject.required()) {
					throw new DependencyException(exception);
				}
			}
			injectors = container.injectors.get(implementation);
		}

		ParameterInjector<?>[] constructParameterInjector(
				Inject inject, ContainerImpl container, Constructor<T> constructor ) throws MissingDependencyException {
			return constructor.getParameterTypes().length == 0
					? null // default constructor.
					: container.getParametersInjectors(
					constructor,
					constructor.getParameterAnnotations(),
					constructor.getParameterTypes(),
					inject.value()
			);
		}

		/**
		 * 找到類implementation的構造器
		 * @param implementation 要處理的類型 
		 * @return
		 */
		@SuppressWarnings("unchecked")
		private Constructor<T> findConstructorIn( Class<T> implementation ) {
			Constructor<T> found = null;
			Constructor<T>[] declaredConstructors = (Constructor<T>[]) implementation.getDeclaredConstructors();
			/**
			 * 對獲取的構造函數進行遍歷,查找出添加了Annotation的構造函數
			 */
			for ( Constructor<T> constructor : declaredConstructors ) {
				if (constructor.getAnnotation(Inject.class) != null) {
					if (found != null) {
						throw new DependencyException("More than one constructor annotated" + " with @Inject found in " + implementation + ".");
					}
					found = constructor;
				}
			}
			if (found != null) {
				return found;
			}

			// If no annotated constructor is found, look for a no-arg constructor
			// instead.
			try {
				return implementation.getDeclaredConstructor();
			} catch ( NoSuchMethodException e ) {
				throw new DependencyException("Could not find a suitable constructor"
						+ " in " + implementation.getName() + ".");
			}
		}

		/**
		 * Construct an instance. Returns {@code Object} instead of {@code T} because it may return a proxy.
		 */
		Object construct( InternalContext context, Class<? super T> expectedType ) {
			ConstructionContext<T> constructionContext =
					context.getConstructionContext(this);

			// We have a circular reference between constructors. Return a proxy.
			if (constructionContext.isConstructing()) {
				// TODO (crazybob): if we can't proxy this object, can we proxy the
				// other object?
				return constructionContext.createProxy(expectedType);
			}

			// If we're re-entering this factory while injecting fields or methods,
			// return the same instance. This prevents infinite loops.
			T t = constructionContext.getCurrentReference();
			if (t != null) {
				return t;
			}

			try {
				// First time through...
				constructionContext.startConstruction();
				try {
					Object[] parameters =
							getParameters(constructor, context, parameterInjectors);
					t = constructor.newInstance(parameters);
					constructionContext.setProxyDelegates(t);
				} finally {
					constructionContext.finishConstruction();
				}

				// Store reference. If an injector re-enters this factory, they'll
				// get the same reference.
				constructionContext.setCurrentReference(t);

				// Inject fields and methods.
				for ( Injector injector : injectors ) {
					injector.inject(context, t);
				}

				return t;
			} catch ( InstantiationException e ) {
				throw new RuntimeException(e);
			} catch ( IllegalAccessException e ) {
				throw new RuntimeException(e);
			} catch ( InvocationTargetException e ) {
				throw new RuntimeException(e);
			} finally {
				constructionContext.removeCurrentReference();
			}
		}
	}
	
	/**
	 * 參數注入器,表示以對象方法方式注入時的一個方法注入形式
	 * @author Administrator
	 *
	 * @param <T>
	 */
	static class ParameterInjector<T> {

		/**
		 * 外部上下文
		 */
		final ExternalContext<T> externalContext;
		/**
		 * 內部工廠
		 */
		final InternalFactory<? extends T> factory;

		public ParameterInjector( ExternalContext<T> externalContext, InternalFactory<? extends T> factory ) {
			this.externalContext = externalContext;
			this.factory = factory;
		}

		/**
		 * 創建一個需要注入到方法參數的對象
		 * @param member 方法
		 * @param context 內部上下文
		 * @return 構造號的參數對象
		 */
		T inject( Member member, InternalContext context ) {
			ExternalContext<?> previous = context.getExternalContext();
			context.setExternalContext(externalContext);
			try {
				/**
				 * 工廠類生成實例對象
				 */
				return factory.create(context);
			} finally {
				context.setExternalContext(previous);
			}
		}
	}

	/**
	 * 取得對象的方法的參數數組
	 * @param member 方法
	 * @param context 內部上下文
	 * @param parameterInjectors 參數的注入器數組
	 * @return 構造號的方法參數數組
	 */
	private static Object[] getParameters( Member member, InternalContext context, ParameterInjector[] parameterInjectors ) {
		if (parameterInjectors == null) {
			return null;
		}

		Object[] parameters = new Object[parameterInjectors.length];
		/**
		 * 遍歷參數,生成對象
		 */
		for ( int i = 0; i < parameters.length; i++ ) {
			parameters[i] = parameterInjectors[i].inject(member, context);
		}
		return parameters;
	}

	/**
	 * 給對象注入其依賴的值或者對象
	 * @param o 需要注入屬性或者對象的對象
	 * @param context 內部上下文
	 */
	void inject( Object o, InternalContext context ) {
		List<Injector> injectors = this.injectors.get(o.getClass());
		for ( Injector injector : injectors ) {
			injector.inject(context, o);
		}
	}

	/**
	 * 給對象注入其依賴的值或者對象
	 * @param <T>
	 * @param implementation
	 * @param context
	 * @return
	 */
	<T> T inject( Class<T> implementation, InternalContext context ) {
		try {
			ConstructorInjector<T> constructor = getConstructor(implementation);
			return implementation.cast(constructor.construct(context, implementation));
		} catch ( Exception e ) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 依照給定的類型和名稱以及內部上下文創建對象的實例
	 * @param <T> 參數類型
	 * @param type 類型
	 * @param name 對象名稱
	 * @param context 內部上下文
	 * @return
	 */
	@SuppressWarnings("unchecked")
	<T> T getInstance( Class<T> type, String name, InternalContext context ) {
		ExternalContext<?> previous = context.getExternalContext();
		Key<T> key = Key.newInstance(type, name);
		context.setExternalContext(ExternalContext.newInstance(null, key, this));
		try {
			InternalFactory o = getFactory(key);
			if (o != null) {
				return getFactory(key).create(context);
			} else {
				return null;
			}
		} finally {
			context.setExternalContext(previous);
		}
	}

	/**
	 * 依照給定的類型和默認名稱以及內部上下文創建對象的實例
	 * @param <T> 參數類型
	 * @param type 類型
	 * @param context 內部上下文
	 * @return
	 */
	<T> T getInstance( Class<T> type, InternalContext context ) {
		return getInstance(type, DEFAULT_NAME, context);
	}

	/**
	 * 注入依賴到已經存在的對象的字段和方法
	 */
	public void inject( final Object o ) {
		callInContext(new ContextualCallable<Void>() {
			public Void call( InternalContext context ) {
				inject(o, context);
				return null;
			}
		});
	}

	/**
	 * 創建並且注入一個新的對應類型的實例
	 */
	public <T> T inject( final Class<T> implementation ) {
		return callInContext(new ContextualCallable<T>() {
			public T call( InternalContext context ) {
				return inject(implementation, context);
			}
		});
	}

	/**
	 * 取得類型的實例對象
	 */
	public <T> T getInstance( final Class<T> type, final String name ) {
		return callInContext(new ContextualCallable<T>() {
			public T call( InternalContext context ) {
				return getInstance(type, name, context);
			}
		});
	}

	/**
	 * 根據默認名稱來取得類型的實例對象(適用於一個類型創建一個默認對象的情況)
	 */
	public <T> T getInstance( final Class<T> type ) {
		return callInContext(new ContextualCallable<T>() {
			public T call( InternalContext context ) {
				return getInstance(type, context);
			}
		});
	}

	/**
	 * 根據類型來取得該類型的實例對象名稱集合(適用於同一個類型創建了多個不同名稱的對象)
	 */
	public Set<String> getInstanceNames( final Class<?> type ) {
		return factoryNamesByType.get(type);
	}

	/**
	 * 本地線程上下文,保存內部上下文對象
	 */
	ThreadLocal<Object[]> localContext =
			new ThreadLocal<Object[]>() {
				@Override
				protected Object[] initialValue() {
					return new Object[1];
				}
			};

	/**
	 * 查找Thread Local的上下文。在必要的情況下,創建(或刪除)一個上下文
	 * Looks up thread local context. Creates (and removes) a new context if necessary.
	 */
	<T> T callInContext( ContextualCallable<T> callable ) {
		Object[] reference = localContext.get();//從localContext中獲取此線程局部變量的當前線程副本中的值。
		/**
		 * 如果其爲空
		 */
		if (reference[0] == null) {
			reference[0] = new InternalContext(this);//創建一個新的InternalContext對象賦值給reference[0]
			try {
				/**
				 * 調用callable中的call方法,並返回結果
				 */
				return callable.call((InternalContext) reference[0]);
			} finally {
				//如果reference[0]是新創建的話,則移除
				reference[0] = null;
				//同時情況localContext
				localContext.remove();
			}
		} else {
			//如果reference[0]不爲空,則直接進行調用
			return callable.call((InternalContext) reference[0]);
		}
	}

	/**
	 * 內部定義的接口
	 * @author Administrator
	 *
	 * @param <T>
	 */
	interface ContextualCallable<T> {
		T call( InternalContext context );
	}

	/**
	 * 根據給定的實現類來找到構造函數
	 * Gets a constructor function for a given implementation class.
	 */
	@SuppressWarnings("unchecked")
	<T> ConstructorInjector<T> getConstructor( Class<T> implementation ) {
		return constructors.get(implementation);
	}

	/**
	 * 作用域策略本地線程
	 */
	final ThreadLocal<Object> localScopeStrategy =
			new ThreadLocal<Object>();

	public void setScopeStrategy( Scope.Strategy scopeStrategy ) {
		this.localScopeStrategy.set(scopeStrategy);
	}

	public void removeScopeStrategy() {
		this.localScopeStrategy.remove();
	}

	/**
	 * 定義一個向對象中注入字段或者方法屬性接口
	 */
	interface Injector extends Serializable {

		void inject( InternalContext context, Object o );
	}

	static class MissingDependencyException extends Exception {

		MissingDependencyException( String message ) {
			super(message);
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章