注入
<!--有参构造方法-->
<bean id="user2" class="com.tj.entity.User">
<constructor-arg name="username" value="张三"></constructor-arg>
<constructor-arg name="password" value="abc123"></constructor-arg>
</bean>
给谁注入:
注入的值:
<bean id="user5" class="com.tj.entity.User">
<property name="username" value="liuliu"></property>
<property name="password" value="ll123"></property>
</bean>
给谁注入:
注入的值:
本质还是调用set方法
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user6" class="com.tj.entity.User"
p:username="hejiujiu" p:password="hj123">
</bean>
</beans>
注入集合数据
List结构的: array,list,set
Map结构的 map,entry,props,prop
只要结构相同,标签可以互换
<!-- 给数组注入数据 -->
<property name="myStrs">
<set>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</set>
</property>
<!-- 注入list集合数据 -->
<property name="myList">
<array>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</array>
</property>
<!-- 注入set集合数据 -->
<property name="mySet">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<!-- 注入Map数据 -->
<property name="myMap">
<props>
<prop key="testA">aaa</prop>
<prop key="testB">bbb</prop>
</props>
</property>
<!-- 注入properties数据 -->
<property name="myProps">
<map>
<entry key="testA" value="aaa">/entry>
<entry key="testB"> <value>bbb</value> </entry>
</map>
</property>
<property name="username" value="#{表达式}"/>
数字值和字符串值:#{123}, #{‘zhangsan’}
引用其他bean值:#{bean的id}
引用其他bean的属性:#{bean的id.属性名}
执行其他bean的方法:#{bean的id.方法名}
引用静态方法或属性:#{T(类路径).属性名/方法名}
前提:需要给对应的属性设置set方法
如果当前People类中的属性名和某个bean的id名一致,那么Spring会自动将bean对象赋值给属性
<bean id="people" class="com.yaorange.entity.Peopele" autowire="byName"/>
如果当前People类中的属性的数据类型和某个bean的Class一致,那么Spring会自动将bean对象赋值给属性
<bean id="people" class="com.yaorange.entity.Peopele" autowire="byType"/>
提示:基于类型的自动注入必须保证在整个Spring容器中只有唯一的一个bean类型满足要求
<?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" default-autowire="byType">
原文:https://www.cnblogs.com/heibaimao123/p/13793579.html