在Spring中,有2个最基本最重要的包,即org.springframework.beans 和org.springframework.context.在这两个包中实现了无侵入式的框架,代码中大量引用了java的反射机制,通过动态调用的方式避免了硬编码,为spring的反向控制特性提供了基础。
在这2个包中,最重要的类是BeanFactory和ApplicationContext。
BeanFactory提供了一种先进的配置机制来管理任何种类的bean。ApplicationContext建立在BeanFactory之上,并增加了其他功能,如国际化,获取资源,事件传递等。
1.在xml配置文件中,bean的标识(id 和 name)
id:指定在benafactory中管理该bean的唯一的标识。name可用来唯一标识bean 或给bean起别名。
2.bean的class
class属性指定了bean的来源,即bean的实际路径。注意要指定全路径,而不可只写类名。
3.Singleton的使用
在spring中,bean可被定义为2中部署模式中的一种。singleton和non-singleton(prototype)模式。
singloeton:只有一个共享的实例存在,所有对这个bean的请求都会返回这个唯一实例。
prototype:对这个bean的每次请求都会都会创建一个新的bean实例。根据已经存在的bean而clone出来的bean。默认为singleton模式。
xml例
<bean id="helloWorld" class="com.gc.action.HelloWorld" singleton="true">
<property name="msg">
<value>HelloChina!</value>
</property>
</bean>
4.bean的属性
spring中,bean的属性值有2种注入方式。setter注入和构造函数注入。
setter注入是在调用无参的构造函数或无参的静态工厂方法实例化配置文档中定义的bean之后,通过调用bean上的setter方法实现的。
构造函数的依赖注入是通过调用带有很多参数的构造方法实现的,每个参数表示一个对象或者属性。
5.对属性null值的处理
<bean id="helloWorld" class="com.gc.action.HelloWorld" singleton="true">
<property name="msg">
<value>null</value>
</property>
</bean>
或者
<bean id="helloWorld" class="com.gc.action.HelloWorld" singleton="true">
<property name="msg">
<null/>
</property>
</bean>
以上等同于this.msg=null
6.使用依赖depends-on
此属性可在使用该bean之前,强制初始化一个或多个bean的初始化。例如
<bean id="searchUserService" class="jp.co.xiehl.service.impl.SearchUserServiceImpl" depends-on="tuserDao">
<property name="tuserDao" ref="tuserDao" />
</bean>