Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的依赖关系。
Spring中,提供了三种主要的装配机制:
- 在XML中进行显式配置;
- 在Java中进行显式配置;
- 隐式的bean发现机制和自动装配;
三种配置方式可以依据具体的项目进行选择,也可以相互搭配进行使用。
1、 通过XML装配bean
使用XML为Spring装配bean之前,需要先创建一个XML文件,以<beans>
元素为根。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
其中,<beans>
是所有Spring配置文件的根元素。
1.1 简单bean的声明
要在基于XML的Spring配置中声明一个bean,需要用到<bean>
,以Student类为例:
<bean class="com.Student"/>
创建这个bean的类通过class属性来指定,且要使用全限定的类名。
在没有给定ID时,bean将根据全限定类名来进行命名,上例中bean的ID将为“com.Student#0”。其中“#0”是计数形式,用来区别相同类型的其他bean。此时,若再声明一个Student的bean,其ID将为“com.Student#1”。
这里,通常在对bean进行设置时,同时设置好ID。
<bean id="student" class="com.Student"/>
注:在bean的声明中,bean的类型是以字符串的形式设置在class属性中,而Spring的XML配置不能从编译期的类型检查中受益。
1.2 借助构造器初始化bean
构造器注入,有两种基本的配置方案可以选择。
<constructor-arg>
元素;- 使用Spring3.0所引入的c-命名空间;
上面已经声明了student bean,现假设有一个Team类,具有接收Student类型的构造器。
class Team{
private Student student;
public Team(Student student){
this.student = student;
}
public Team(){
}
}
现在采用<constructor-arg>
元素来构造Team bean。
<bean id="team" class="com.Team">
<constructor-arg ref="student"/>
</bean>
当Spring遇到这个<bean>