案例一:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- configuration for this bean go here -->
</bean>
<!-- configuration for this bean go here -->
<bean id="..." class="...">
</bean>
<!-- more bean definitions go here -->
</beans>
id属性:定义单个bean组件的命名。
class属性:定义了bean使用的类,要使用类的全称来定义。(fully qualified classname)
案例二:
<bean id="car" class="com.yl.Car">
<constructor-arg value="Audi"/>
<constructor-arg ref="Shanghai"/>
<constructor-arg value="300000"/>
</bean>
在构造bean的时候,可以使用constructor-arg元素来提供额外信息,如果不配置constructor-arg元素,spring将会使用bean的默认构造器。
value属性:赋予构造参数的属性值,此构造参数应为简单类型。
ref属性:把bean的引用赋予给构造器。
案例三:
package web;
public class Tom {
private int number;
private PersonalInfo personalInfo;
public Tom() {
}
public void setNumber(int number) {
this.number = number;
}
public void serPersonalInfo(PersonalInfo personalInfo) {
this.personalInfo = personInfo;
}
}
<bean id="tom" class="web.Tom">
<property name="number" value="15"/>
<property name="personalInfo" ref="scoreList"/>
</bean
如果spring使用setter方式注入,要使用property元素来给bean提供信息。
name属性:表示要注入bean的beans属性名。
value属性:表示给bean属性注入的值。
ref属性:表示给bean属性注入另一个bean的引用
property元素会指示spring调用set()方法来为属性设置值,也会根据bean属性的类型来判断value值的正确类型。