一、bean基础
1、bean的基本定义
2、bean的作用域
3、bean实例,配置合作者bean
bean中需要使用其他bean时需要使用ref属性
<?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-3.0.xsd"> <bean id="student" class="com.ru.domain.Student"> <!-- collaborators and configuration for this bean go here --> <property name="id" value="1"/> <property name="name" value="如神"/> <property name="age" value="23"/> </bean> <!-- 引用其他的bean实例 --> <bean id="clazz" class="com.ru.domain.Clazz"> <property name="id" value="01"/> <property name="name" value="1班"/> <!-- 这个引用了student对象实例,使用ref属性 --> <property name="stu" ref="student"/> </bean> </beans>
二、bean注入
1、通过构造函数注入值
通过构造函数注入,需要在bean中创建构造方法。
注意:spring不会区分构造参数的顺序,并且把参数类型都解释成string型。
bean
public class Student { private Integer id; private String name; private Integer age; public Student(Integer id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } public Student(String name, Integer age) { super(); this.name = name; this.age = age; } public Student(Integer id, String name) { super(); this.id = id; this.name = name; }
beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="student" class="com.ru.domain.Student"> <!-- <property name="id" value="1"/> <property name="name" value="如神"/> <property name="age" value="23"/> --> <!-- index表示构造函数里的第几个参数。type是参数的类型,这样写可以避免在有多个构造函数是造成spring的赋值错误 --> <constructor-arg index="1" type="java.lang.String" value="伟"/> <constructor-arg index="0" type="java.lang.Integer" value="1"/> <!-- <constructor-arg value="24"/> --> </bean> </beans>
2、通过属性值注入,调用bean的set方法
ref引用的是bean的id
<bean id="clazz" class="com.ru.domain.Clazz"> <property name="id" value="01"/> <property name="name" value="1班"/> <!-- 这个引用了student对象实例,使用ref属性 --> <property name="stu" ref="student"/> </bean>
3、自动装配
4、注入嵌套bean
嵌套的bean不可以被spring访问