Spring配置文件applicationContext.xml中bean>>property>>name属性的含义
程序员文章站
2022-05-21 23:08:34
...
Spring配置文件applicationContext.xml中bean>>property>>name属性表示的含义
首先我们知道property是bean元素的子元素,它用于调用Bean实例中的setter方法用于完成属性赋值,从而实现依赖注入。其name属性表示Bean实例中的相应属性,ref属性用于指定其属性值(就是你要连接的bean的id)
例子:
<?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-4.3.xsd">
<bean id="userDao" class="com.itheima.userDaoImpl">
<bean id="customerDao" class="com.itheima.customerDaoImpl">
<bean id="service" class="com.itheima.serviceDaoImpl">
<property name="age" ref="userDao">
<property name="phone" ref="customerDao">
</beans>
例如:
<bean id="service" class="com.itheima.serviceDaoImpl">
<property name="age" ref="userDao">
<property name="phone" ref="customerDao">
对于这个bean,在 Service类中必须存在:
setAge(String string){}
setPhone(String string){}
这两个方法;
如果没有这两个setter方法或者name属性的值不是(Age/age)(Phone/phone)就会报错:
Bean property ‘某某属性’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?