spring在进行装配bean时,提供了三种主要的装配机制:(今天说的是通过xml装配bean)
- 自动化装配bean
- 通过java代码装配bean
- 通过xml装配bean
- 通过xml装配bean
步骤:
(1)创建xml配置规范
Spring XML配置(约束)如下
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
(2)声明<bean>
<bean id = "book" class = "com.study.Book">
</bean>
创建这个bean的类通过class属性来指定的,id就是用来表示class的
(3)借助构造器注入或Setter方法注入初始化bean
构造器注入:
<bean id="book" class="com.study.Book">-->
<constructor-arg name="bookName" value="红楼梦">
</constructor-arg>
</bean>
Setter方法注入:
<bean id="book" class="com.study.Book">-->
<property name="bookName" value="红楼梦"></property>
</bean>