3.1、Bean标签的基本配置
用于配置对象交由Spring来创建
默认情况下它调用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功。
基本属性:
-
id :Bean实例在Spring容器中的唯一标识。
-
class: Bean的全限定名称。
<bean class="com.yl.dao.impl.StudentDaoImpl" id="studentDao" scope="prototype"></bean>
3.2、Bean标签的范围配置
scope:指对象的作用范围,取值如下,
在要注入属性的bean标签中进行配置,前提是该类有提供属性值对应的set方法。
<bean class="com.yl.domain.Student" id="student" >
<property name="name" value="王祖贤"></property>
<property name="id" value="1"></property>
<property name="age" value="24"></property>
</bean>
public class Demo {
public static void main(String[] args) {
// 创建IOC容器,传入配置文件名
// ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象,使用强制转换
// 通过bean属性来修改Student类中属性值
Student student = (Student) app.getBean("student");
System.out.println(student);
}
}
/*前提是student类中要有set方法否则就会报错
NotWritablePropertyException:
Invalid property 'name' of bean class [com.yl.domain.Student]:
Bean property 'name' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
*/
如果类中有引用类型的变量
value表示变量的值
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.xsd">
<bean class="com.yl.dao.impl.StudentDaoImpl" id="studentDao" scope="singleton"></bean>
<bean class="com.yl.domain.Dog" id="dog" >
<property name="color" value="白色"></property>
</bean>
<bean class="com.yl.domain.Student" id="student" >
<property name="name" value="王祖贤"></property>
<property name="id" value="1"></property>
<property name="age" value="24"></property>
<!-- 如果Student中还有Dog(引用类型属性)就可以使用ref-->
<property name="dog" ref="dog"></property>
</bean>
<bean class="com.yl.domain.Student" id="student2" >
<constructor-arg name="name" value="张三"></constructor-arg>
<constructor-arg name="id" value="01"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="dog" ref="dog"></constructor-arg>
</bean>
</beans>
二、Spring注解开发