Spring核心容器的理论很简单:String核心容器就是一个超级大工厂,所有的对象(包括数据源、Hibernate SessionFactory等基础性资源)都会被当成Spring核心容器管理的对象——
Spring把容器中的一起对象统称为Bean。
Spring对Bean没有任何要求。只要是一个Java类,Spring就可管理该Java类,并将它当成Bean处理。
Spring容器怎么知道管理那些Bean呢?
答案是:XML配置文件或者是注解。
Spring对XML配置文件的文件名没有任何要求,可以随意指定。
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
beans
xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns
=
"http://www.springframework.org/schema/beans"
xsi:schemaLocation
=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
>
<
bean
id
=
"person"
class
=
"org.crazyit.app.service.Person"
>
<
property
name
=
"axe"
ref
=
"axe"
/>
</
bean
>
<
bean
id
=
"axe"
class
=
"org.crazyit.app.service.Axe"
/>
<
bean
id
=
"win"
class
=
"javax.swing.JFrame"
/>
<
bean
id
=
"date"
class
=
"java.util.Date"
/>
</
beans
>
注解:
<property.../>子元素通常用于作为<bean.../>元素的子元素,它驱动Spring在底层以反射执行一次setter方法。name属性决定执行哪个类属性的setter方法,而value或ref决定执行setter方法的传入参数。
接下来程序就可通过Spring容器来访问容器中的Bean,ApplicationnContext是Spring容器最常用的接口,该接口有如下两个实现类:
1、ClassPathXmlApplicationContext:从类加载路径下搜索配置文件,并根据配置文件来创建Spring容器。
2、FileSystemXmlApplicationContext:从文件系统的相对路径或绝对路径下去搜索配置文件,并根据配置文件来创建Spring容器。
对于java项目而言,类加载路径总是稳定的,因此通常总是使用ClassPathXmlApplicationContext创建Spring容器。
public
class
BeanTest {
public
static
void
main(String[]
args
)
throws
Exception {
ApplicationContext
ctx
=
new
ClassPathXmlApplicationContext(
"beans.xml"
);
Person
p
=
ctx
.getBean(
"person"
, Person.
class
);
p
.useAxe();
}
}
/*
Spring容器获取Bean对象主要有如下两个方法。
Object getBean(String id):根据容器中Bean的id来获取指定Bean,获取Bean之后需要进行强制类型转换。
T getBean(String name,Class<T> requiredType):根据容器中Bean的id来获取指定Bean,但该方法带一个泛型参数,因此获取Bean之后无须进行强制类型转换。
*/