spring容器的一些理解

getBean方法得到context中的bean,传入的参数是name。 java

有理由相信,context中有一个map,map的key就是name,value则是一个beanFactory。 redis

疑问:接口或者抽象类能够导入context吗? spring

答案:不能。setNameAware这些须要对context配置中的类调用setName方法。虽然abstract能够产生class文件,但他被反射建立倒是不能够的。 spa

spring找那些能够装入容器的class文件,会把这些class实现的接口以及继承自的父类信息都会添加到context中。因此在spring.xml文件中看到抽象类定义时,须要加上abstract="true"标志。 代理

<bean id="redisDao" class="com.ec.dao.impl.RedisDao" abstract="true">
		<property name="config" ref="config" />
		<property name="redisConnectionPool" ref="redisConnectionPool" />
		<property name="redisConnectionPool1" ref="redisConnectionPool1" />
	</bean>

说spring保存了class的接口信息和parent class信息是有根据的。在咱们使用bean时,经过@Resource标签,咱们只是定义一个接口,spring就能够把实现该接口的对象注入。当有多个实现时,就得用到@Autowired,经过定义bean name来注入。 code


充分利用了反射机制: xml

想象一下吧,若是没有反射机制,xml中的这些bean该如何被产生?咱们本身new?那spring也就没有太多存在的价值了。 对象

在反射机制之上,利用代理实现AOP,也就显得那么顺其天然了。 继承

private final static Class[] constructorParams =
    { InvocationHandler.class };    
public static Object newProxyInstance(ClassLoader loader,
					  Class[] interfaces,
					  InvocationHandler h)
	throws IllegalArgumentException
    {
	if (h == null) {
	    throw new NullPointerException();
	}

	/*
	 * Look up or generate the designated proxy class.
	 */
	Class cl = getProxyClass(loader, interfaces);

	/*
	 * Invoke its constructor with the designated invocation handler.
	 */
	try {
	    Constructor cons = cl.getConstructor(constructorParams);
	    return (Object) cons.newInstance(new Object[] { h });
	} catch (NoSuchMethodException e) {
	    throw new InternalError(e.toString());
	} catch (IllegalAccessException e) {
	    throw new InternalError(e.toString());
	} catch (InstantiationException e) {
	    throw new InternalError(e.toString());
	} catch (InvocationTargetException e) {
	    throw new InternalError(e.toString());
	}
    }
再看看
InvocationHandler.class
是个什么玩意

public Object invoke(Object proxy, Method method, Object[] args)
	throws Throwable;
返回的Object里面能够动态实现一些接口,spring就能够在模板中利用这些接口来作文章了。
相关文章
相关标签/搜索