Bean:在Spring中,那些组成你应用程序的主体(backbone)及由SpringIOC容器所管理的对象,被称之为bean。简单地讲,bean就是由Spring容器初始化、装配及管理的对象,除此之外,bean就与应用程序中的其他对象没有什么区别了。而bean定义以及bean相互间的依赖关系将通过配置元数据来描述。
org.springframework.beans.factory.BeanFactory是SpringIoC容器的实际代表者,IoC容器负责容纳此前所描述的bean,并对bean进行管理,包括:实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。
SpringIoC容器可以通过多种途径来加载配置元数据,比如本地文件系统、JavaCLASSPATH等(貌似URL也行)。
Spring3之IoC容器的实例化
SpringIoC容器的实例化非常简单,可以用ClassPathXmlApplicationContextorFileSystemXmlApplicationContext类来完成,AnnotationConfigApplicationContext也可以用注解来完成。
a).XML式
包名:com.spring305.test.iocInstance
文件列表:BeanA.java,BeanB.java,IocInstance.java,IocInstanceA.xml,在此包下有一包temp,另有一份测试配置文件IocInstance.xml
代码如下:
BeanA.java
BeanB.java
public class BeanA {
private int id;
private String name;
public BeanA() {
}
public BeanA(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void testMethod(){
System.out.println(BeanA.class);
}
setter,getter
}
public class BeanA {
private int id;
private String name;
public BeanA() {
}
public BeanA(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void testMethod(){
System.out.println(BeanA.class);
}
setter,getter
}
IocInstanceA.xml
<!-- 下面是引用XML的路径及写法注释,使用时只保留一个,并且对应相应路径 -->
<!-- 这二种表示这个引入的文件要与本XML文件在同一级目录中
<import resource="IocInstance.xml"/>
<import resource="/IocInstance.xml"/>
下面二种表示在当前XML目录中temp文件夹下面
<import resource="temp/IocInstance.xml"/>
<import resource="/temp/IocInstance.xml"/>
-->
<!-- 这下面的一个是相对路径的书写方式,引入根目录下的XML文件,
<import resource="../../../../IocInstance.xml"/>
-->
<!--
classpath:这种方式可以使用但是,在spring3的英文文档中并不推荐使用,推荐使用用../到父目录中或者/到下级目录来找,因为classpath:可能在部署的时候引向不正确的目录
<import resource="classpath:IocInstance.xml"/>
-->
<!-- 下面的这种方式也是可以的,但是,也不被推荐,原因同上,如果采用这二种情况,spring3建议把路径写上,然后用${}来引入 -->
<import resource="file:D:/workspace/MyEclipseSSH/Spring305/src/IocInstance.xml"/>
<bean id="beanA" class="com.spring305.test.iocInstance.BeanA"></bean>
src目录下IocInstance.xml ,主要是用来测试从一个XML文件引入另外一个文件来实例化的,它和temp包下的IocInstance.xml的内容一样也只有beanB这个bean,后者主要是用来测试路径的。
IocInstance.xml
-
<beanid="beanB"class="com.spring305.test.iocInstance.BeanB"></bean>
本文介绍Spring框架中IoC容器的概念及其两种实例化方法:XML配置和注解配置。通过具体代码示例展示了如何使用ClassPathXmlApplicationContext和FileSystemXmlApplicationContext加载XML配置文件,以及如何使用AnnotationConfigApplicationContext来通过注解配置Bean。

1586

被折叠的 条评论
为什么被折叠?



