目录
第一节 Spring依赖注入Bean属性(xml)
1.1 手动装配,使用xml配置
1. 通过构造方法注入
- 写一个Student类,提供get/set、toString、无参构造、2种不同的有参构造
- 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.xsd">
<!--通过构造方法注入属性的值-->
<!--<bean class="com.it.model.Student" id="student">
<!–这样写就调用的是2个string的构造方法–>
<constructor-arg name="username" value="shu"></constructor-arg>
<constructor-arg name="password" value="123"></constructor-arg>
</bean>-->
<!--<bean class="com.it.model.Student" id="student">
<!–这样写就调用的是一个string 一个是int 的构造方法–>
<constructor-arg name="username" value="shu"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
</bean>-->
<bean class="com.it.model.Student" id="student">
<!--还可以通过索引加类型,给构造方法赋值-->
<constructor-arg index="0" value="shu" type="java.lang.String"></constructor-arg>
<constructor-arg index="1" value="18" type="int"></constructor-arg>
</bean>
</beans>
- 效果
2. 通过属性的setter方法注入
- setter方法有两种注入,一般使用第一种直观
- beans1.xml
- 效果
3. 通过p命名空间注入【了解】
- 使用这种方法的类,必须要给属性提供get/set方法,否则报错
- beans2.xml
- 效果
1.2 SpEL表达式【了解】
- SpEL:Spring 表达式
- 对<property>进行统一编程,所有的内容都使用value。
- <property name="" value="#{表达式}">
#{123}、#{‘jack’} : 数字、字符串
#{beanId} :另一个bean引用
#{beanId.propName} :操作数据
#{beanId.toString()} :执行方法
#{T(类).字段|方法} :静态方法或字段
演示
- 提供Address属性的get/set方法、重写toString
- 提供Customer属性的get/set方法、重写toString(toString无需包含地址)
- beans3.xml